From 6d72da5217eec2f673c30ebf3abdc96d0c439347 Mon Sep 17 00:00:00 2001 From: Aisuko Date: Mon, 30 Oct 2023 01:49:42 +0000 Subject: [PATCH] Remove OAM Signed-off-by: GitHub --- Makefile | 5 +- adapter/adapter.go | 7 +- adapter/error.go | 64 ++---- adapter/logger.go | 20 -- adapter/meshmodel.go | 107 --------- adapter/oam.go | 488 ------------------------------------------ adapter/operations.go | 8 - api/grpc/handlers.go | 17 -- go.mod | 1 - go.sum | 2 - 10 files changed, 27 insertions(+), 692 deletions(-) delete mode 100644 adapter/meshmodel.go delete mode 100644 adapter/oam.go diff --git a/Makefile b/Makefile index 0c9f1b2..076bfc6 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,7 @@ -.PHONY: lint tidy verify +.PHONY: check +check: lint +check: tidy +check: verify lint: diff --git a/adapter/adapter.go b/adapter/adapter.go index efdbf38..1cf41ff 100644 --- a/adapter/adapter.go +++ b/adapter/adapter.go @@ -33,11 +33,8 @@ type Handler interface { // CreateInstance(*chan interface{}) error // Instantiates clients used in deploying and managing mesh instances, e.g. Kubernetes clients. ApplyOperation(context.Context, OperationRequest) error // Applies an adapter operation. This is adapter specific and needs to be implemented by each adapter. ListOperations() (Operations, error) // List all operations an adapter supports. - ProcessOAM(ctx context.Context, srv OAMRequest) (string, error) - - // Need not implement this method and can be reused - StreamErr(*meshes.EventsResponse, error) // Streams an error event, e.g. to a channel - StreamInfo(*meshes.EventsResponse) // Streams an informational event, e.g. to a channel + StreamErr(*meshes.EventsResponse, error) // Streams an error event, e.g. to a channel + StreamInfo(*meshes.EventsResponse) // Streams an informational event, e.g. to a channel } // Adapter contains all handlers, channels, clients, and other parameters for an adapter. diff --git a/adapter/error.go b/adapter/error.go index 1fbcf17..78a24b4 100644 --- a/adapter/error.go +++ b/adapter/error.go @@ -19,30 +19,27 @@ import ( ) const ( - ErrGetNameCode = "1000" - ErrCreateInstanceCode = "1001" - ErrMeshConfigCode = "1002" - ErrValidateKubeconfigCode = "1003" - ErrClientConfigCode = "1004" - ErrClientSetCode = "1005" - ErrStreamEventCode = "1006" - ErrOpInvalidCode = "1007" - ErrApplyOperationCode = "1008" - ErrListOperationsCode = "1009" - ErrNewSmiCode = "1010" - ErrRunSmiCode = "1011" - ErrNoResponseCode = "1011" - ErrOpenOAMDefintionFileCode = "1013" - ErrOpenOAMRefFileCode = "1014" - ErrJSONMarshalCode = "1015" - ErrOAMRetryCode = "1016" - ErrSmiInitCode = "1007" - ErrInstallSmiCode = "1008" - ErrConnectSmiCode = "1009" - ErrDeleteSmiCode = "1010" - ErrGenerateComponentsCode = "1011" - ErrAuthInfosInvalidMsgCode = "1012" - ErrCreatingComponentsCode = "1013" + ErrGetNameCode = "1000" + ErrCreateInstanceCode = "1001" + ErrMeshConfigCode = "1002" + ErrValidateKubeconfigCode = "1003" + ErrClientConfigCode = "1004" + ErrClientSetCode = "1005" + ErrStreamEventCode = "1006" + ErrOpInvalidCode = "1007" + ErrApplyOperationCode = "1008" + ErrListOperationsCode = "1009" + ErrNewSmiCode = "1010" + ErrRunSmiCode = "1011" + ErrNoResponseCode = "1011" + ErrJSONMarshalCode = "1015" + ErrSmiInitCode = "1007" + ErrInstallSmiCode = "1008" + ErrConnectSmiCode = "1009" + ErrDeleteSmiCode = "1010" + ErrGenerateComponentsCode = "1011" + ErrAuthInfosInvalidMsgCode = "1012" + ErrCreatingComponentsCode = "1013" ) var ( @@ -116,25 +113,6 @@ func ErrDeleteSmi(err error) error { return errors.New(ErrDeleteSmiCode, errors.Alert, []string{"Error deleting smi tool: %s"}, []string{err.Error()}, []string{}, []string{}) } -// ErrOpenOAMDefintionFile is the error for opening OAM Definition file -func ErrOpenOAMDefintionFile(err error) error { - return errors.New(ErrOpenOAMDefintionFileCode, errors.Alert, []string{"error opening OAM Definition File: %s"}, []string{err.Error()}, []string{}, []string{}) -} - -// ErrOpenOAMRefFile is the error for opening OAM Schema Ref file -func ErrOpenOAMRefFile(err error) error { - return errors.New(ErrOpenOAMRefFileCode, errors.Alert, []string{"error opening OAM Schema Ref File: %s"}, []string{err.Error()}, []string{}, []string{}) -} - -// ErrJSONMarshal is the error for json marhal failure -func ErrJSONMarshal(err error) error { - return errors.New(ErrOAMRetryCode, errors.Alert, []string{"error marshal JSON: %s"}, []string{err.Error()}, []string{}, []string{}) -} - -func ErrOAMRetry(err error) error { - return errors.New(ErrOAMRetryCode, errors.Alert, []string{"error marshal JSON: %s"}, []string{err.Error()}, []string{}, []string{}) -} - // will be depracated func ErrGenerateComponents(err error) error { return errors.New(ErrGenerateComponentsCode, errors.Alert, []string{"error generating components"}, []string{err.Error()}, []string{"Invalid component generation method passed, Some invalid field passed in DynamicComponentsConfig"}, []string{"Pass the correct GenerationMethod in DynamicComponentsConfig", "Pass the correct fields in DynamicComponentsConfig"}) diff --git a/adapter/logger.go b/adapter/logger.go index eab5d0d..304eafc 100644 --- a/adapter/logger.go +++ b/adapter/logger.go @@ -48,15 +48,6 @@ func (s *adapterLogger) GetComponentInfo(svc interface{}) error { return s.next.GetComponentInfo(svc) } -// func (s *adapterLogger) CreateInstance(c *chan interface{}) error { -// s.log.Info("Creating instance") -// err := s.next.CreateInstance(c) -// if err != nil { -// s.log.Error(err) -// } -// return err -// } - func (s *adapterLogger) ApplyOperation(ctx context.Context, op OperationRequest) error { s.log.Info("Applying operation ", op.OperationName) err := s.next.ApplyOperation(ctx, op) @@ -66,17 +57,6 @@ func (s *adapterLogger) ApplyOperation(ctx context.Context, op OperationRequest) return err } -// ProcessOAM wraps the Handler's ProcessOAM method along with relevant logging -func (s *adapterLogger) ProcessOAM(ctx context.Context, oamRequest OAMRequest) (string, error) { - s.log.Info("Process OAM components") - msg, err := s.next.ProcessOAM(ctx, oamRequest) - if err != nil { - s.log.Error(err) - } - - return msg, err -} - func (s *adapterLogger) ListOperations() (Operations, error) { s.log.Info("Listing Operations") ops, err := s.next.ListOperations() diff --git a/adapter/meshmodel.go b/adapter/meshmodel.go deleted file mode 100644 index 917c77d..0000000 --- a/adapter/meshmodel.go +++ /dev/null @@ -1,107 +0,0 @@ -package adapter - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "os" - "time" - - backoff "github.com/cenkalti/backoff/v4" - "github.com/layer5io/meshkit/models/meshmodel/core/types" - "github.com/layer5io/meshkit/models/meshmodel/core/v1alpha1" - "github.com/layer5io/meshkit/models/meshmodel/registry" -) - -// MeshModelRegistrantDefinitionPath - Structure for configuring registrant paths -type MeshModelRegistrantDefinitionPath struct { - // EntityDefinitionPath holds the path for Entity Definition file - EntityDefintionPath string - - Type types.CapabilityType - // Host is the address of the gRPC host capable of processing the request - Host string - Port int -} - -// MeshModel provides utility functions for registering -// MeshModel components to a registry in a reliable way -type MeshModelRegistrant struct { - Paths []MeshModelRegistrantDefinitionPath - HTTPRegistry string -} - -// NewOAMRegistrant returns an instance of OAMRegistrant -func NewMeshModelRegistrant(paths []MeshModelRegistrantDefinitionPath, HTTPRegistry string) *MeshModelRegistrant { - return &MeshModelRegistrant{ - Paths: paths, - HTTPRegistry: HTTPRegistry, - } -} - -// Register will register each capability individually to the OAM Capability registry -// -// It sends a POST request to the endpoint in the "OAMHTTPRegistry", if the request -// fails then the request is retried. It uses exponential backoff algorithm to determine -// the interval between in the retries. It will retry only for 10 mins and will stop retrying -// after that. -// -// Register function is a blocking function -func (or *MeshModelRegistrant) Register(ctxID string) error { - for _, dpath := range or.Paths { - var mrd registry.MeshModelRegistrantData - definition, err := os.Open(dpath.EntityDefintionPath) - if err != nil { - return ErrOpenOAMDefintionFile(err) - } - mrd.Host = registry.Host{ - Hostname: dpath.Host, - Port: dpath.Port, - Metadata: ctxID, - } - mrd.EntityType = dpath.Type - switch dpath.Type { - case types.ComponentDefinition: - var cd v1alpha1.ComponentDefinition - if err := json.NewDecoder(definition).Decode(&cd); err != nil { - _ = definition.Close() - return ErrJSONMarshal(err) - } - _ = definition.Close() - enbyt, _ := json.Marshal(cd) - mrd.Entity = enbyt - // send request to the register - backoffOpt := backoff.NewExponentialBackOff() - backoffOpt.MaxElapsedTime = 10 * time.Minute - if err := backoff.Retry(func() error { - contentByt, err := json.Marshal(mrd) - if err != nil { - return backoff.Permanent(err) - } - content := bytes.NewReader(contentByt) - - // host here is given by the application itself and is trustworthy hence, - // #nosec - resp, err := http.Post(or.HTTPRegistry, "application/json", content) - if err != nil { - return err - } - if resp.StatusCode != http.StatusCreated && - resp.StatusCode != http.StatusOK && - resp.StatusCode != http.StatusAccepted { - return fmt.Errorf( - "register process failed, host returned status: %s with status code %d", - resp.Status, - resp.StatusCode, - ) - } - return nil - }, backoffOpt); err != nil { - return ErrOAMRetry(err) - } - } - } - - return nil -} diff --git a/adapter/oam.go b/adapter/oam.go deleted file mode 100644 index 07e8e65..0000000 --- a/adapter/oam.go +++ /dev/null @@ -1,488 +0,0 @@ -package adapter - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "os" - "path/filepath" - "strings" - "time" - - backoff "github.com/cenkalti/backoff/v4" - meshmodel "github.com/layer5io/meshkit/models/meshmodel/core/v1alpha1" - "github.com/layer5io/meshkit/models/oam/core/v1alpha1" - "github.com/layer5io/meshkit/utils" - "github.com/layer5io/meshkit/utils/manifests" -) - -const ( - // OAM Metadata constants - OAMAdapterNameMetadataKey = "adapter.meshery.io/name" - OAMComponentCategoryMetadataKey = "ui.meshery.io/category" - - //Runtime generation methods - Manifests = "MANIFESTS" - HelmCHARTS = "HELM_CHARTS" -) - -// ProcessOAM processes OAM components. This is adapter specific and needs to be implemented by each adapter. -func (h *Adapter) ProcessOAM(context.Context, OAMRequest) (string, error) { - return "", nil -} - -// OAMRegistrant provides utility functions for registering -// OAM components to a registry in a reliable way -type OAMRegistrant struct { - // Paths is a slice for holding the paths of OAMDefitions, - // OAMRefSchema and Host on the filesystem - // - // OAMRegistrant will read the definitions from these - // paths and will register them to the OAM registry - Paths []OAMRegistrantDefinitionPath - - // OAMHTTPRegistry is the address of an OAM registry - OAMHTTPRegistry string -} - -// OAMRegistrantDefinitionPath - Structure for configuring registrant paths -type OAMRegistrantDefinitionPath struct { - // OAMDefinitionPath holds the path for OAM Definition file - OAMDefintionPath string - // OAMRefSchemaPath holds the path for the OAM Ref Schema file - OAMRefSchemaPath string - // Host is the address of the gRPC host capable of processing the request - Host string - // Restricted should be set to true if this capability should be restricted - // only to the server and shouldn't be exposed to the user for direct usage - Restricted bool - // Metadata is the other data which can be attached to the post request body - // - // Metadata like name of the component, etc. - Metadata map[string]string -} - -// OAMRegistrantData struct defines the body of the POST request that is sent to the OAM -// registry (Meshery) -// -// The body contains the -// 1. OAM definition, which is in accordance with the OAM spec -// 2. OAMRefSchema, which is json schema draft-4, draft-7 or draft-8 for the corresponding OAM object -// 3. Host is this service's grpc address in the form of `hostname:port` -// 4. Restricted should be set to true if the given capability is meant to be used internally -// 5. Metadata can be a map of key value pairs -type OAMRegistrantData struct { - OAMDefinition interface{} `json:"oam_definition,omitempty"` - OAMRefSchema string `json:"oam_ref_schema,omitempty"` - Host string `json:"host,omitempty"` - Restricted bool `json:"restricted,omitempty"` - Metadata map[string]string `json:"metadata,omitempty"` -} - -// NewOAMRegistrant returns an instance of OAMRegistrant -func NewOAMRegistrant(paths []OAMRegistrantDefinitionPath, oamHTTPRegistry string) *OAMRegistrant { - return &OAMRegistrant{ - Paths: paths, - OAMHTTPRegistry: oamHTTPRegistry, - } -} - -// Register will register each capability individually to the OAM Capability registry -// -// It sends a POST request to the endpoint in the "OAMHTTPRegistry", if the request -// fails then the request is retried. It uses exponential backoff algorithm to determine -// the interval between in the retries. It will retry only for 10 mins and will stop retrying -// after that. -// -// Register function is a blocking function -func (or *OAMRegistrant) Register() error { - for _, dpath := range or.Paths { - var ord OAMRegistrantData - - definition, err := os.Open(dpath.OAMDefintionPath) - if err != nil { - return ErrOpenOAMDefintionFile(err) - } - - definitionMap := map[string]interface{}{} - if err = json.NewDecoder(definition).Decode(&definitionMap); err != nil { - _ = definition.Close() - return ErrJSONMarshal(err) - } - _ = definition.Close() - ord.OAMDefinition = definitionMap - - schema, err := os.ReadFile(dpath.OAMRefSchemaPath) - if err != nil { - return ErrOpenOAMRefFile(err) - } - if string(schema) == "" { //since this component is unusable if it doesn't have oam_ref_schema - continue - } - formatTitleInOAMRefSchema(&schema) - - ord.OAMRefSchema = string(schema) - - ord.Host = dpath.Host - ord.Metadata = dpath.Metadata - ord.Restricted = dpath.Restricted - - // send request to the register - backoffOpt := backoff.NewExponentialBackOff() - backoffOpt.MaxElapsedTime = 10 * time.Minute - if err := backoff.Retry(func() error { - contentByt, err := json.Marshal(ord) - if err != nil { - return backoff.Permanent(err) - } - content := bytes.NewReader(contentByt) - - // host here is given by the application itself and is trustworthy hence, - // #nosec - resp, err := http.Post(or.OAMHTTPRegistry, "application/json", content) - if err != nil { - return err - } - - if resp.StatusCode != http.StatusCreated && - resp.StatusCode != http.StatusOK && - resp.StatusCode != http.StatusAccepted { - return fmt.Errorf( - "register process failed, host returned status: %s with status code %d", - resp.Status, - resp.StatusCode, - ) - } - - return nil - }, backoffOpt); err != nil { - return ErrOAMRetry(err) - } - } - - return nil -} - -type MeshModelConfig struct { - Category string - CategoryMetadata map[string]interface{} - Metadata map[string]interface{} -} - -// StaticCompConfig is used to configure CreateComponents -type StaticCompConfig struct { - MeshModelName string //Used in Adding ModelName onto Core Meshmodel components. Pass it the same as meshName in OAM components - URL string //URL - Method string //Use the constants exported by package. Manifests or Helm - MeshModelPath string - MeshModelConfig MeshModelConfig - DirName string //The directory's name. By convention, it should be the version name - Config manifests.Config //Filters required to create definition and schema - Force bool //When set to true, if the file with same name already exists, they will be overridden -} - -// CreateComponents generates components for a given configuration and stores them. -func CreateComponents(scfg StaticCompConfig) error { - meshmodeldirName, _ := getLatestDirectory(scfg.MeshModelPath) - meshmodelDir := filepath.Join(scfg.MeshModelPath, scfg.DirName) - _, err := os.Stat(meshmodelDir) - if err != nil && os.IsNotExist(err) { - err = os.Mkdir(meshmodelDir, 0777) - if err != nil { - return ErrCreatingComponents(err) - } - } - var comp *manifests.Component - switch scfg.Method { - case Manifests: - comp, err = manifests.GetFromManifest(context.Background(), scfg.URL, manifests.SERVICE_MESH, scfg.Config) - case HelmCHARTS: - comp, err = manifests.GetFromHelm(context.Background(), scfg.URL, manifests.SERVICE_MESH, scfg.Config) - default: - return ErrCreatingComponents(errors.New("invalid generation method. Must be either Manifests or HelmCharts")) - } - if err != nil { - return ErrCreatingComponents(err) - } - if comp == nil { - return ErrCreatingComponents(errors.New("no components found")) - } - - for i, def := range comp.Definitions { - schema := comp.Schemas[i] - name := getNameFromWorkloadDefinition([]byte(def)) - meshmodelFileName := name + "_meshmodel.json" - err = createMeshModelComponentsFromLegacyOAMComponents([]byte(def), schema, filepath.Join(meshmodelDir, meshmodelFileName), scfg.MeshModelName, scfg.MeshModelConfig) - if err != nil { - return ErrCreatingComponents(err) - } - } - //For Meshmodel components - if meshmodeldirName != "" { - err = copyCoreComponentsToNewVersion(filepath.Join(scfg.MeshModelPath, meshmodeldirName), filepath.Join(scfg.MeshModelPath, scfg.DirName), scfg.DirName, true) - if err != nil { - return ErrCreatingComponents(err) - } - } - return nil -} -func convertOAMtoMeshmodel(def []byte, schema string, isCore bool, meshmodelname string, mcfg MeshModelConfig) ([]byte, error) { - var oamdef v1alpha1.WorkloadDefinition - err := json.Unmarshal(def, &oamdef) - if err != nil { - return nil, err - } - var c meshmodel.ComponentDefinition - c.Metadata = make(map[string]interface{}) - metaname := strings.Split(manifests.FormatToReadableString(oamdef.ObjectMeta.Name), ".") - var displayname string - if len(metaname) > 0 { - displayname = metaname[0] - } - c.DisplayName = displayname - c.Model.Category = meshmodel.Category{ - Name: mcfg.Category, - } - if mcfg.CategoryMetadata != nil { - c.Model.Category.Metadata = mcfg.CategoryMetadata - } - c.Metadata = mcfg.Metadata - if isCore { - c.APIVersion = oamdef.APIVersion - c.Kind = oamdef.ObjectMeta.Name - c.Model.Version = oamdef.Spec.Metadata["version"] - c.Model.Name = meshmodelname - } else { - c.APIVersion = oamdef.Spec.Metadata["k8sAPIVersion"] - c.Kind = oamdef.Spec.Metadata["k8sKind"] - c.Model.Version = oamdef.Spec.Metadata["meshVersion"] - c.Model.Name = oamdef.Spec.Metadata["meshName"] - } - c.Model.DisplayName = manifests.FormatToReadableString(c.Model.Name) - c.Model.Name = strings.ToLower(c.Model.Name) - c.Model.Metadata = c.Metadata - c.Format = meshmodel.JSON - c.Schema = schema - byt, err := json.Marshal(c) - if err != nil { - return nil, err - } - return byt, nil -} - -// TODO: After OAM is completely removed from meshkit, replace this with fetching native meshmodel components. For now, reuse OAM functions -func createMeshModelComponentsFromLegacyOAMComponents(def []byte, schema string, path string, meshmodel string, mcfg MeshModelConfig) (err error) { - byt, err := convertOAMtoMeshmodel(def, schema, false, meshmodel, mcfg) - if err != nil { - return err - } - err = writeToFile(path, byt, true) - return -} - -// Meshery core components are versioned alongside their corresponding Adapter components, -// which, in turn, are versioned with respect to the infrastructure under management; e.g. "Istio Mesh". -// Every time that managed components are generated for a new infrastructure version (e.g. service mesh version), -// the latest core components are to be replicated (copied) and assigned the latest infrastructure version. -// The schema of the replicated core components can be augmented or left as-is depending upon the need to do so. -func copyCoreComponentsToNewVersion(fromDir string, toDir string, newVersion string, isMeshmodel bool) error { - files, err := os.ReadDir(fromDir) - if err != nil { - return err - } - for _, f := range files { - //core definition file or core schema file - if !strings.Contains(strings.TrimSuffix(f.Name(), ".json"), ".") || !strings.Contains(strings.TrimSuffix(f.Name(), ".meshery.layer5io.schema.json"), ".") { - fsource, err := os.Open(filepath.Join(fromDir, f.Name())) - if err != nil { - return err - } - defer fsource.Close() - content, err := io.ReadAll(fsource) - if err != nil { - return err - } - //only for definition files - if !strings.Contains(strings.TrimSuffix(f.Name(), ".json"), ".") { - if isMeshmodel { - content, err = modifyMeshmodelVersionInDefinition(content, newVersion) - } else { - content, err = modifyVersionInDefinition(content, newVersion) - } - if err != nil { - return err - } - } - err = writeToFile(filepath.Join(toDir, f.Name()), content, false) - if err != nil { - return err - } - } - } - return nil -} -func modifyMeshmodelVersionInDefinition(old []byte, newversion string) (new []byte, err error) { - var def meshmodel.ComponentDefinition - err = json.Unmarshal(old, &def) - if err != nil { - return - } - def.Model.Version = newversion - new, err = json.Marshal(def) - return -} -func modifyVersionInDefinition(old []byte, newversion string) (new []byte, err error) { - var def v1alpha1.WorkloadDefinition - err = json.Unmarshal(old, &def) - if err != nil { - return - } - if def.Spec.Metadata == nil { //to avoid panic - def.Spec.Metadata = make(map[string]string) - } - def.Spec.Metadata["version"] = newversion - new, err = json.Marshal(def) - return -} -func getLatestDirectory(path string) (string, error) { - files, err := os.ReadDir(path) - if err != nil { - return "", err - } - filenames := []string{} - for _, f := range files { - filenames = append(filenames, f.Name()) - } - filenames = utils.SortDottedStringsByDigits(filenames) - if len(filenames) != 0 { - return filenames[len(filenames)-1], nil - } - return "", fmt.Errorf("no directory found") -} - -// create a file with this filename and stuff the string -func writeToFile(path string, data []byte, force bool) error { - _, err := os.Stat(path) - if err != nil && !os.IsNotExist(err) { //There some other error than non existence of file - return err - } - - if err == nil { //file already exists - if !force { // Dont override existing file, skip it - fmt.Println("File already exists,skipping...") - return nil - } - err := os.Remove(path) //Remove the existing file, before overriding it - if err != nil { - return err - } - } - return os.WriteFile(path, data, 0666) -} - -// getNameFromWorkloadDefinition takes out name from workload definition -func getNameFromWorkloadDefinition(definition []byte) string { - var wd v1alpha1.WorkloadDefinition - err := json.Unmarshal(definition, &wd) - if err != nil { - return "" - } - return wd.Spec.DefinitionRef.Name -} - -// This will be depracated once all adapters migrate to new method of component creation( using static config) and registeration -type DynamicComponentsConfig struct { - TimeoutInMinutes time.Duration - URL string - GenerationMethod string - Config manifests.Config - Operation string -} - -func RegisterWorkLoadsDynamically(runtime, host string, dc *DynamicComponentsConfig) error { - var comp *manifests.Component - var err error - switch dc.GenerationMethod { - case Manifests: - comp, err = manifests.GetFromManifest(context.Background(), dc.URL, manifests.SERVICE_MESH, dc.Config) - case HelmCHARTS: - comp, err = manifests.GetFromHelm(context.Background(), dc.URL, manifests.SERVICE_MESH, dc.Config) - default: - return ErrGenerateComponents(errors.New("failed to generate components")) - } - if err != nil { - return ErrGenerateComponents(err) - } - if comp == nil { - return ErrGenerateComponents(errors.New("failed to generate components")) - } - for i, def := range comp.Definitions { - var ord OAMRegistrantData - ord.OAMRefSchema = comp.Schemas[i] - - //Marshalling the stringified json - ord.Host = host - definitionMap := map[string]interface{}{} - if err := json.Unmarshal([]byte(def), &definitionMap); err != nil { - return err - } - definitionMap["apiVersion"] = "core.oam.dev/v1alpha1" - definitionMap["kind"] = "WorkloadDefinition" - ord.OAMDefinition = definitionMap - ord.Metadata = map[string]string{ - OAMAdapterNameMetadataKey: dc.Operation, - } - // send request to the register - backoffOpt := backoff.NewExponentialBackOff() - backoffOpt.MaxElapsedTime = time.Minute * dc.TimeoutInMinutes - if err := backoff.Retry(func() error { - contentByt, err := json.Marshal(ord) - if err != nil { - return backoff.Permanent(err) - } - content := bytes.NewReader(contentByt) - // host here is given by the application itself and is trustworthy hence, - // #nosec - resp, err := http.Post(fmt.Sprintf("%s/api/oam/workload", runtime), "application/json", content) - if err != nil { - return err - } - if resp.StatusCode != http.StatusCreated && - resp.StatusCode != http.StatusOK && - resp.StatusCode != http.StatusAccepted { - return fmt.Errorf( - "register process failed, host returned status: %s with status code %d", - resp.Status, - resp.StatusCode, - ) - } - - return nil - }, backoffOpt); err != nil { - return err - } - } - return nil -} - -func formatTitleInOAMRefSchema(schema *[]byte) { - var schemamap map[string]interface{} - err := json.Unmarshal(*schema, &schemamap) - if err != nil { - return - } - title, ok := schemamap["title"].(string) - if !ok { - return - } - - schemamap["title"] = manifests.FormatToReadableString(title) - (*schema), err = json.Marshal(schemamap) - if err != nil { - return - } -} diff --git a/adapter/operations.go b/adapter/operations.go index 1c55813..c8117e7 100644 --- a/adapter/operations.go +++ b/adapter/operations.go @@ -75,14 +75,6 @@ type OperationRequest struct { Version string // Service mesh version to be installed, defaults to latest version. } -type OAMRequest struct { - Username string - DeleteOp bool - OamComps []string - OamConfig string - K8sConfigs []string -} - // List all operations an adapter supports. func (h *Adapter) ListOperations() (Operations, error) { operations := make(Operations) diff --git a/api/grpc/handlers.go b/api/grpc/handlers.go index 53f3a59..196e0ef 100644 --- a/api/grpc/handlers.go +++ b/api/grpc/handlers.go @@ -23,7 +23,6 @@ import ( "context" ) - // MeshName is the handler function for the method MeshName. func (s *Service) MeshName(ctx context.Context, req *meshes.MeshNameRequest) (*meshes.MeshNameResponse, error) { return &meshes.MeshNameResponse{ @@ -113,21 +112,6 @@ func (s *Service) StreamEvents(ctx *meshes.EventsRequest, srv meshes.MeshService } } -// ProcessOAM is the handler function for the method ProcessOAM -func (s *Service) ProcessOAM(ctx context.Context, srv *meshes.ProcessOAMRequest) (*meshes.ProcessOAMResponse, error) { - operation := adapter.OAMRequest{ - Username: srv.Username, - DeleteOp: srv.DeleteOp, - OamComps: srv.OamComps, - OamConfig: srv.OamConfig, - K8sConfigs: srv.KubeConfigs, - } - - msg, err := s.Handler.ProcessOAM(ctx, operation) - return &meshes.ProcessOAMResponse{Message: msg}, err -} - -// ProcessOAM is the handler function for the method ProcessOAM func (s *Service) MeshVersions(context.Context, *meshes.MeshVersionsRequest) (*meshes.MeshVersionsResponse, error) { versions := make([]string, 0) return &meshes.MeshVersionsResponse{ @@ -135,7 +119,6 @@ func (s *Service) MeshVersions(context.Context, *meshes.MeshVersionsRequest) (*m }, nil } -// ProcessOAM is the handler function for the method ProcessOAM func (s *Service) ComponentInfo(context.Context, *meshes.ComponentInfoRequest) (*meshes.ComponentInfoResponse, error) { err := s.Handler.GetComponentInfo(s) if err != nil { diff --git a/go.mod b/go.mod index 6d74fbf..3afe0f7 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,6 @@ go 1.21 replace github.com/kudobuilder/kuttl => github.com/layer5io/kuttl v0.4.1-0.20200806180306-b7e46afd657f require ( - github.com/cenkalti/backoff/v4 v4.2.1 github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.0.1 github.com/layer5io/learn-layer5/smi-conformance v0.0.0-20210317075357-06b4f88b3e34 github.com/layer5io/meshkit v0.6.77 diff --git a/go.sum b/go.sum index ffcbd19..dda1426 100644 --- a/go.sum +++ b/go.sum @@ -113,8 +113,6 @@ github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b h1:otBG+dV+YK+Soembj github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b/go.mod h1:obH5gd0BsqsP2LwDJ9aOkm/6J86V6lyAXCoQWGw3K50= github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0 h1:nvj0OLI3YqYXer/kZD8Ri1aaunCxIEsOst1BVJswV0o= github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE= -github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= -github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=