diff --git a/cyclops-collectors/blockstorage-collector/README.md b/cyclops-collectors/blockstorage-collector/README.md new file mode 100644 index 0000000..958a6a9 --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/README.md @@ -0,0 +1,25 @@ +# BLOCK STORAGE COLLECTOR + +OpenStack Block Storage collector written in go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` diff --git a/cyclops-collectors/blockstorage-collector/collector/collector.go b/cyclops-collectors/blockstorage-collector/collector/collector.go new file mode 100644 index 0000000..ea1c8b2 --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/collector/collector.go @@ -0,0 +1,445 @@ +package main + +import ( + "context" + "os" + "strconv" + "strings" + "time" + + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack" + "github.com/gophercloud/gophercloud/openstack/blockstorage/v3/volumes" + "github.com/gophercloud/gophercloud/openstack/identity/v3/projects" + "github.com/gophercloud/gophercloud/pagination" + "github.com/prometheus/client_golang/prometheus" + datamodels "gitlab.com/cyclops-utilities/datamodels" + eeEvent "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/event_management" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + collector = "Blockstorage" + objects = "volume" + remotelist []*eeModels.MinimalState + collectionStart int64 +) + +// collect handles the process of retrieving the information from the system. +func collect() { + + l.Trace.Printf("[COLLECTION] The collection process has been started.\n") + + collectionStart = time.Now().UnixNano() + + metricTime.With(prometheus.Labels{"type": "Collection Start Time"}).Set(float64(collectionStart)) + + // Here comes the logic to retrieve the information from the system + opts := gophercloud.AuthOptions{ + DomainName: cfg.OpenStack.Domain, + IdentityEndpoint: cfg.OpenStack.Keystone, + Password: cfg.OpenStack.Password, + Username: cfg.OpenStack.User, + } + + if len(cfg.OpenStack.Project) > 0 { + + opts.TenantName = cfg.OpenStack.Project + + } + + provider, e := openstack.AuthenticatedClient(opts) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error authenticating against OpenStack. Error: %v\n", e) + + os.Exit(1) + + } + + listOpts := projects.ListOpts{ + Enabled: gophercloud.Enabled, + } + + authClient, e := openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{}) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error creating the collector client. Error: %v\n", e) + + os.Exit(1) + + } + + allPages, e := projects.List(authClient, listOpts).AllPages() + + if e != nil { + + l.Error.Printf("[COLLECTION] Error listing all the pages. Error: %v\n", e) + + os.Exit(1) + + } + + allProjects, e := projects.ExtractProjects(allPages) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error listing all the projects. Error: %v\n", e) + + os.Exit(1) + + } + + l.Trace.Printf("[COLLECTION] Querying events engine service for list of known and not terminated volumes") + + resourceType := "blockstorage" + eeParams := eeEvent.NewListStatesParams().WithResource(&resourceType).WithRegion(&cfg.OpenStack.Region) + + ctx, _ := context.WithTimeout(context.Background(), 300*time.Second) + r, e := reportClient.EventManagement.ListStates(ctx, eeParams) + + // Clears the remotelist between runs + remotelist = nil + + if e != nil { + + l.Warning.Printf("[COLLECTION] Something went wrong while retrieving the usage from EventsEngine, check with the administrator. Error: %v.\n", e) + + } else { + + remotelist = r.Payload + + } + + resourceType = "blockstorage_ssd" + eeParams = eeEvent.NewListStatesParams().WithResource(&resourceType).WithRegion(&cfg.OpenStack.Region) + + ctx, _ = context.WithTimeout(context.Background(), 300*time.Second) + r, e = reportClient.EventManagement.ListStates(ctx, eeParams) + + if e != nil { + + l.Warning.Printf("[COLLECTION] Something went wrong while retrieving the usage(ssd) from EventsEngine, check with the administrator. Error: %v.\n", e) + + } else { + + remotelist = append(remotelist, r.Payload...) + + } + + eeCount := len(remotelist) + apiCount := 0 + ssdCount := 0 + + l.Trace.Printf("[COLLECTION] (BEFORE) Existing count of blockstorage elements at remote [ %v ].\n", len(remotelist)) + +allProjectsLoop: + for _, project := range allProjects { + + l.Trace.Printf("[COLLECTION] Found project [ %v ] with ID [ %v ]. Proceeding to get list of volumes.\n", project.Name, project.ID) + + volumeClient, e := openstack.NewBlockStorageV3(provider, gophercloud.EndpointOpts{ + Region: cfg.OpenStack.Region, + }) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error creating block storage client. Error: %v\n", e) + + continue + + } + + // Filter by project id: + for _, filter := range cfg.ProjectFilters { + + if strings.Contains(project.ID, filter) && filter != "" { + + l.Debug.Printf("[COLLECTION] The Project [ %v ] matches filter [ %v ] and won't be further processed.", project.ID, filter) + + continue allProjectsLoop + + } + + } + + // Filter by project name: + for _, filter := range cfg.NameFilters { + + if strings.Contains(strings.ToLower(project.Name), strings.ToLower(filter)) && filter != "" { + + l.Debug.Printf("[COLLECTION] The Project [ %v ] matches filter [ %v ] and won't be further processed.", project.Name, filter) + + continue allProjectsLoop + + } + + } + + opts := volumes.ListOpts{ + AllTenants: true, + TenantID: project.ID, + } + + pager := volumes.List(volumeClient, opts) + + e = pager.EachPage(func(page pagination.Page) (bool, error) { + + vList, e := volumes.ExtractVolumes(page) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error processing the lists of active resources. Error: %v\n", e) + + return false, e + + } + + apiCount += len(vList) + + for _, v := range vList { + + // "v" will be a volumes.Volume + l.Trace.Printf("[COLLECTION] Found volume [ %v ] with ID [ %v ]. Parameters: Status [ %v ], Type [ %v ], Size [ %v ] Zone [ %v ] and Replication [ %v ].\n", + strings.TrimSpace(v.Name), v.ID, v.Status, v.VolumeType, v.Size, v.AvailabilityZone, v.ReplicationStatus) + + // Here comes the transformation of the information retrieved into either + md := make(datamodels.JSONdb) + md["size"] = strconv.Itoa(v.Size) + md["availabilityzone"] = v.AvailabilityZone + md["replication"] = v.ReplicationStatus + md["volumetype"] = v.VolumeType + md["region"] = cfg.OpenStack.Region + + evTime := int64(time.Now().Unix()) + evLast := getStatus(v.Status) + + objectType := "blockstorage" + + if strings.Contains(v.VolumeType, "ssd") { + + objectType = "blockstorage_ssd" + ssdCount++ + + } + + // events or usage reports to be sent. + event := eeModels.Event{ + Account: project.ID, + EventTime: &evTime, + LastEvent: &evLast, + MetaData: md, + Region: cfg.OpenStack.Region, + ResourceID: v.ID, + ResourceName: strings.TrimSpace(v.Name), + ResourceType: objectType, + } + + report(event) + + //if this object exists in remote list then lets remove it + for i, object := range remotelist { + + metadata := object.MetaData + + if strings.Compare(object.Account, project.ID) == 0 && + strings.Compare(object.ResourceID, v.ID) == 0 && + strings.Compare(object.ResourceName, v.Name) == 0 && + strings.Compare(metadata["size"].(string), strconv.Itoa(v.Size)) == 0 { + + l.Debug.Printf("[COLLECTION] Event send cleaned from the processing list..\n") + + remotelist = append(remotelist[:i], remotelist[i+1:]...) + + break + + } + + } + + } + + return true, nil + + }) + + } + + l.Trace.Printf("[COLLECTION] (AFTER) Remaining count of blockstorage elements at remote which were left unprocessed [ %v ].\n", len(remotelist)) + + for _, object := range remotelist { + + l.Debug.Printf("[COLLECTION] Sending termination for zombie data in the system..\n") + + evTime := int64(time.Now().Unix()) + evLast := getStatus("terminated") + + objectType := "blockstorage" + + if strings.Contains(object.MetaData["volumetype"].(string), "ssd") { + + objectType = "blockstorage_ssd" + + } + + // events or usage reports to be sent. + event := eeModels.Event{ + Account: object.Account, + EventTime: &evTime, + LastEvent: &evLast, + MetaData: object.MetaData, + Region: cfg.OpenStack.Region, + ResourceID: object.ResourceID, + ResourceName: object.ResourceName, + ResourceType: objectType, + } + + report(event) + + } + + metricCount.With(prometheus.Labels{"type": "Total Storage Blocks reported by OS API"}).Set(float64(apiCount)) + + metricCount.With(prometheus.Labels{"type": "Total Storage Blocks (only SSD) reported by OS API"}).Set(float64(ssdCount)) + + metricCount.With(prometheus.Labels{"type": "Total Storage Blocks from EventEngine"}).Set(float64(eeCount)) + + metricCount.With(prometheus.Labels{"type": "Total Storage Blocks forcefully TERMINATED"}).Set(float64(len(remotelist))) + + metricTime.With(prometheus.Labels{"type": "Collection Processing Time"}).Set(float64(time.Now().UnixNano()-collectionStart) / float64(time.Millisecond)) + + l.Warning.Printf("[COLLECTION] Completed.\n - OS Report: %v\n - EE Report: %v\n - Forced Termination: %v\n - Processing Time: %v[ms]\n", apiCount, eeCount, len(remotelist), float64(time.Now().UnixNano()-collectionStart)/float64(time.Millisecond)) + + l.Trace.Printf("[COLLECTION] The collection process has been finished.\n") + + return + +} + +// getStatus job is to normalize the event state returned by the collectors. +// Parameters: +// - state: string returned by the system. +// Returns: +// - status: normalized state to be returned. +func getStatus(state string) (status string) { + + switch strings.ToUpper(state) { + + case "ACTIVE": + + status = "active" + + case "ATTACHING": + + status = "active" + + case "AVAILABLE": + + status = "active" + + case "BUILD": + + status = "inactive" + + case "CREATING": + + status = "active" + + case "DELETED": + + status = "terminated" + + case "DELETING": + + status = "terminated" + + case "DETACHING": + + status = "active" + + case "DOWN": + + status = "inactive" + + case "ERROR": + + status = "error" + + case "ERROR_DELETING": + + status = "error" + + case "EXTENDING": + + status = "inactive" + + case "HARD_DELETED": + + status = "terminated" + + case "IN-USE": + + status = "active" + + case "MAINTENANCE": + + status = "active" + + case "PAUSED": + + status = "inactive" + + case "RESCUED": + + status = "active" + + case "RESIZE": + + status = "active" + + case "RESIZED": + + status = "active" + + case "RESERVED": + + status = "active" + + case "RETYPING": + + status = "inactive" + + case "SHUTOFF": + + status = "terminated" + + case "SOFT_DELETED": + + status = "terminated" + + case "STOPPED": + + status = "inactive" + + case "SUSPENDED": + + status = "inactive" + + case "TERMINATED": + + status = "terminated" + + case "VERIFY_RESIZE": + + status = "active" + + } + + l.Trace.Printf("[REPORT] State received from the system [ %v ] normalized to [ %v ]", state, status) + + return status + +} diff --git a/cyclops-collectors/blockstorage-collector/collector/config.go b/cyclops-collectors/blockstorage-collector/collector/config.go new file mode 100644 index 0000000..b31a94d --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/collector/config.go @@ -0,0 +1,246 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool + Key string + Place string + Token string +} + +type configuration struct { + APIKey apiKey + General generalConfig + Heappe heappeConfig + Kafka kafkaConfig + Keycloak keycloakConfig + Lieutenant lieutenantConfig + OpenStack openStackConfig + Prometheus prometheusConfig + RGW rgwConfig + NameFilters []string + ProjectFilters []string + Services map[string]string +} + +type generalConfig struct { + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ObjectsPeriodicity int + Periodicity int + PrometheusPeriodicity int +} + +type heappeConfig struct { + Username string + Password string + GroupResourceUsageReportURI string + AuthenticateUserPasswordURI string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TLSEnabled bool + TopicUDR string + TopicEEngine string +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type lieutenantConfig struct { + Host string + Token string +} + +type openStackConfig struct { + Domain string + Keystone string + Password string + Project string + Region string + User string +} + +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +type rgwConfig struct { + AccessKeyID string + AdminPath string + Region string + SecretAccessKey string + ServerURL string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.Heappe.Username = masked(c.Heappe.Username, 4) + cfgCopy.Heappe.Password = masked(c.Heappe.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + cfgCopy.Lieutenant.Token = masked(c.Lieutenant.Token, 4) + cfgCopy.OpenStack.Password = masked(c.OpenStack.Password, 4) + cfgCopy.RGW.AccessKeyID = masked(c.RGW.AccessKeyID, 4) + cfgCopy.RGW.SecretAccessKey = masked(c.RGW.SecretAccessKey, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + General: generalConfig{ + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ObjectsPeriodicity: viper.GetInt("general.objectsperiodicity"), + Periodicity: viper.GetInt("general.periodicity"), + PrometheusPeriodicity: viper.GetInt("general.prometheusperiodicity"), + }, + + Heappe: heappeConfig{ + Username: viper.GetString("heappe.username"), + Password: viper.GetString("heappe.password"), + GroupResourceUsageReportURI: viper.GetString("heappe.groupResourceUsageReportUri"), + AuthenticateUserPasswordURI: viper.GetString("heappe.authenticateUserPasswordUri"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + TopicUDR: viper.GetString("kafka.topicudr"), + TopicEEngine: viper.GetString("kafka.topiceengine"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + Lieutenant: lieutenantConfig{ + Host: viper.GetString("lieutenant.host"), + Token: viper.GetString("lieutenant.token"), + }, + + OpenStack: openStackConfig{ + Domain: viper.GetString("openstack.domain"), + Keystone: viper.GetString("openstack.keystone"), + Password: viper.GetString("openstack.password"), + Project: viper.GetString("openstack.project"), + Region: viper.GetString("openstack.region"), + User: viper.GetString("openstack.user"), + }, + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + + RGW: rgwConfig{ + AccessKeyID: viper.GetString("rgw.accesskey"), + AdminPath: viper.GetString("rgw.adminpath"), + Region: viper.GetString("rgw.region"), + SecretAccessKey: viper.GetString("rgw.secretaccesskey"), + ServerURL: viper.GetString("rgw.serverurl"), + }, + + NameFilters: viper.GetStringSlice("events.namefilters"), + ProjectFilters: viper.GetStringSlice("events.projectfilters"), + Services: viper.GetStringMapString("services"), + } + + return + +} diff --git a/cyclops-collectors/blockstorage-collector/collector/kafka.go b/cyclops-collectors/blockstorage-collector/collector/kafka.go new file mode 100644 index 0000000..b265a2a --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/collector/kafka.go @@ -0,0 +1,137 @@ +package main + +import ( + "context" + "crypto/tls" + "encoding/json" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/segmentio/kafka-go" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaHandlerConf struct { + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + channel chan interface{} +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.out != nil { + + for _, p := range kH.out { + + go kafkaSender(p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Go Channel Problems"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Kafka Stream Problems"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "OK", "reason": "Object sent"}).Inc() + + } + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "JSON Marshalling"}).Inc() + + } + + return + + }() + + } + +} diff --git a/cyclops-collectors/blockstorage-collector/collector/main.go b/cyclops-collectors/blockstorage-collector/collector/main.go new file mode 100644 index 0000000..e00cb47 --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/collector/main.go @@ -0,0 +1,188 @@ +package main + +import ( + "flag" + "fmt" + "net/url" + "os" + "reflect" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/spf13/viper" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + eeClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + version string + cfg configuration + pipeU chan interface{} + pipeE chan interface{} + reportClient *eeClient.EventEngineManagementAPI + zombiesClient *cusClient.CustomerDatabaseManagement +) + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Returns: +// - ch: a interface{} channel to be able to send things through the kafka topic +// generated. +func kafkaStart() (chUDR, chEvents chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + chUDR = make(chan interface{}, 1000) + chEvents = make(chan interface{}, 1000) + + handler := kafkaHandlerConf{ + out: []kafkaPackage{ + { + topic: cfg.Kafka.TopicUDR, + channel: chUDR, + }, + { + topic: cfg.Kafka.TopicEEngine, + channel: chEvents, + }, + }, + } + + kafkaHandler(handler) + + return + +} + +// report handles the process of sending the event or usage to the respective +// service. +// Parameters: +// - object: an interface{} reference with the event/usage to be sent. +func report(object interface{}) { + + l.Trace.Printf("[REPORT] The reporting process has been started.\n") + + if reflect.TypeOf(object) == reflect.TypeOf(udrModels.Usage{}) { + + l.Trace.Printf("[REPORT] UDR Object detected. Sending through kafka.\n") + + pipeU <- object + + return + + } + + if reflect.TypeOf(object) == reflect.TypeOf(eeModels.Event{}) { + + l.Trace.Printf("[REPORT] Event Object detected. Sending through kafka.\n") + + pipeE <- object + + return + + } + + fail := "the provided object doesn't belong to UDR or EE models" + + l.Warning.Printf("[REPORT] Something went wrong while processing the object, check with the administrator. Error: %v.\n", fail) + + return + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: Collector-TYPE -conf=/path/to/configuration/file\n") + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %s\nCorrect usage: Collector-TYPE -conf=/path/to/configuration/file\n", err) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs Collector TYPE version %v initialized\n", version) + + dumpConfig(cfg) + + // Let's start the HTTP Server and Gauges for Prometheus + prometheusStart() + +} + +func main() { + + // If needed here is the initialization for the kafka sender: + pipeU, pipeE = kafkaStart() + + // Here we start the client instantiation to send reports to the EventsEngine. + eeConfig := eeClient.Config{ + URL: &url.URL{ + Host: cfg.Services["eventsengine"], + Path: eeClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + reportClient = eeClient.New(eeConfig) + + // Here we start the client instantiation to get the canceled customers to check for zombies. + cusConfig := cusClient.Config{ + URL: &url.URL{ + Host: cfg.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + zombiesClient = cusClient.New(cusConfig) + + // Let's lunch the first collection process.. + go collect() + + // cfg.General.Periodicity should be changed to cfg.General.ObjectPeriodicity + // in the case you need the long (8h) periodicity. + for range time.NewTicker(time.Duration(cfg.General.Periodicity) * time.Minute).C { + + go collect() + + } + +} diff --git a/cyclops-collectors/blockstorage-collector/collector/metrics.go b/cyclops-collectors/blockstorage-collector/collector/metrics.go new file mode 100644 index 0000000..4f7d9ec --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/collector/metrics.go @@ -0,0 +1,95 @@ +package main + +import ( + "log" + "net/http" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricReporting *prometheus.GaugeVec + metricCollection *prometheus.GaugeVec + metricTime *prometheus.GaugeVec + metricCount *prometheus.GaugeVec +) + +func prometheusStart() { + + reg := prometheus.NewPedanticRegistry() + + metricReporting = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "kafka_send_state", + Help: "Reporting information and Kafka topics usage", + }, + []string{ + "reason", + "state", + "topic", + }, + ) + + metricCollection = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "Collection", + Help: "Collection information and usages data", + }, + []string{ + "account", + "event", + "reason", + "state", + "type", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "collection_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + metricCount = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: objects + "_count", + Help: "Different VM Counts", + }, + []string{ + "type", + }, + ) + + reg.MustRegister(metricReporting, metricCollection, metricTime, metricCount) + //prometheus.MustRegister(metricReporting, metricCollection) + + l.Trace.Printf("[Prometheus] Starting to serve the metrics.\n") + + go func() { + + if cfg.Prometheus.MetricsExport { + + //http.Handle(cfg.Prometheus.MetricsRoute, promhttp.Handler()) + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) + + go log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + } + + }() + +} diff --git a/cyclops-collectors/blockstorage-collector/go.mod b/cyclops-collectors/blockstorage-collector/go.mod new file mode 100644 index 0000000..0d28d1c --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/go.mod @@ -0,0 +1,23 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/cyclops-collectors/blockstorage-collector + +go 1.13 + +require ( + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/swag v0.19.15 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/gophercloud/gophercloud v0.23.0 + github.com/magiconair/properties v1.8.5 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/segmentio/kafka-go v0.4.23 + github.com/spf13/afero v1.6.0 // indirect + github.com/spf13/viper v1.9.0 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1 // indirect +) diff --git a/cyclops-collectors/blockstorage-collector/run/cert.crt b/cyclops-collectors/blockstorage-collector/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/cyclops-collectors/blockstorage-collector/run/config.toml b/cyclops-collectors/blockstorage-collector/run/config.toml new file mode 100644 index 0000000..17d47d4 --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/run/config.toml @@ -0,0 +1,93 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# collector! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[EVENTS] +Filters = [ "filter1", "filter2", "filter3" ] + +[GENERAL] +LogFile = "" +LogToConsole = true +# loglevel values can be one of the following: TRACE, DEBUG, INFO, WARNING, ERROR +LogLevel = "TRACE" +ObjectsPeriodicity = 480 +Periodicity = 15 +PrometheusPeriodicity = 60 + +[HEAPPE] +Username = "" +Password = "" +GroupResourceUsageReportUri = "" +AuthenticateUserPasswordUri = "" + +[KAFKA] +Brokers = [ "broker-1-IP:broker-1-PORT", "broker-2-IP:broker-2-PORT", "broker-3-IP:broker-3-PORT" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMax = 10e6 +SizeMin = 10e3 +TLSEnabled = false +TopicEEngine = "Events" +TopicUDR = "UDR" + +[KEYCLOAK] +ClientID = "SERVICE" +ClientSecret = "00000000-0000-0000-0000-00000000" +Enabled = true +Host = "0.0.0.0" +Port = 8080 +Realm = "Development" +RedirectURL = "" +UseHttp = true + +[LIEUTENANT] +Host = "lieutenant:4010" +Token = "" + +[OPENSTACK] +Domain = "" +Keystone = "" +Password = "" +Project = "" +Region = "" +User = "" + +[PROMETHEUS] +Host = "prometheus:9000" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + +[RGW] +AccessKey = "" +AdminPath = "" +Region = "" +SecretAccessKey = "" +ServerURL = "" + +[SERVICES] +CustomerDB = "localhost:8400" +EventsEngine = "localhost:8500" diff --git a/cyclops-collectors/blockstorage-collector/run/docker-compose.yml b/cyclops-collectors/blockstorage-collector/run/docker-compose.yml new file mode 100644 index 0000000..0c874b4 --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/run/docker-compose.yml @@ -0,0 +1,17 @@ +version: '3' + +services: + + collectors: + environment: + WAIT_AFTER_HOSTS: 30 + image: blockstorage-collector:latest + networks: + - collectorsnet + restart: always + volumes: + - ${PWD}/config.toml:/config.toml + +networks: + collectorsnet: + driver: bridge diff --git a/cyclops-collectors/blockstorage-collector/run/key.key b/cyclops-collectors/blockstorage-collector/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/blockstorage-collector/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/cyclops-collectors/network-collector/README.md b/cyclops-collectors/network-collector/README.md new file mode 100644 index 0000000..370c54d --- /dev/null +++ b/cyclops-collectors/network-collector/README.md @@ -0,0 +1,25 @@ +# NETWORK COLLECTOR + +OpenStack Network collector written in go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` diff --git a/cyclops-collectors/network-collector/collector/collector.go b/cyclops-collectors/network-collector/collector/collector.go new file mode 100644 index 0000000..58f3a61 --- /dev/null +++ b/cyclops-collectors/network-collector/collector/collector.go @@ -0,0 +1,402 @@ +package main + +import ( + "context" + "os" + "strings" + "time" + + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack" + "github.com/gophercloud/gophercloud/openstack/identity/v3/projects" + "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/floatingips" + "github.com/gophercloud/gophercloud/pagination" + "github.com/prometheus/client_golang/prometheus" + datamodels "gitlab.com/cyclops-utilities/datamodels" + eeEvent "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/event_management" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + collector = "Network" + objects = "ip" + remotelist []*eeModels.MinimalState + collectionStart int64 +) + +// collect handles the process of retrieving the information from the system. +func collect() { + + l.Trace.Printf("[COLLECTION] The collection process has been started.\n") + + collectionStart = time.Now().UnixNano() + + metricTime.With(prometheus.Labels{"type": "Collection Start Time"}).Set(float64(collectionStart)) + + opts := gophercloud.AuthOptions{ + IdentityEndpoint: cfg.OpenStack.Keystone, + Username: cfg.OpenStack.User, + Password: cfg.OpenStack.Password, + DomainName: cfg.OpenStack.Domain, + } + + if len(cfg.OpenStack.Project) > 0 { + + opts.TenantName = cfg.OpenStack.Project + + } + + provider, e := openstack.AuthenticatedClient(opts) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error authenticating against OpenStack. Error: %v\n", e) + + os.Exit(1) + + } + + listOpts := projects.ListOpts{ + Enabled: gophercloud.Enabled, + } + + authClient, e := openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{}) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error creating the collector client. Error: %v\n", e) + + os.Exit(1) + + } + + allPages, e := projects.List(authClient, listOpts).AllPages() + + if e != nil { + + l.Error.Printf("[COLLECTION] Error listing all the pages. Error: %v\n", e) + + os.Exit(1) + + } + + allProjects, e := projects.ExtractProjects(allPages) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error listing all the projects. Error: %v\n", e) + + os.Exit(1) + + } + + l.Trace.Printf("[COLLECTION] Querying events engine service for list of known and not terminated floating ips") + + resourceType := "floatingip" + + eeParams := eeEvent.NewListStatesParams().WithResource(&resourceType).WithRegion(&cfg.OpenStack.Region) + + ctx, _ := context.WithTimeout(context.Background(), 300*time.Second) + r, e := reportClient.EventManagement.ListStates(ctx, eeParams) + + // Clears the remotelist between runs + remotelist = nil + + if e != nil { + + l.Warning.Printf("[COLLECTION] Something went wrong while retrieving the usage from the system, check with the administrator. Error: %v.\n", e) + + } else { + + remotelist = r.Payload + + } + + eeCount := len(remotelist) + apiCount := 0 + + l.Trace.Printf("[COLLECTION] (BEFORE) Existing count of floating IPs at remote [ %v ].\n", len(remotelist)) + +allProjectsLoop: + for _, project := range allProjects { + + l.Trace.Printf("[COLLECTION] Found project [ %v ] with ID [ %v ]. Proceeding to get list of floating IPs.\n", project.Name, project.ID) + + networkClient, e := openstack.NewNetworkV2(provider, gophercloud.EndpointOpts{ + Region: cfg.OpenStack.Region, + }) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error creating network client. Error: %v\n", e) + + continue + + } + + opts := floatingips.ListOpts{ + TenantID: project.ID, + } + + // Filter by project id: + for _, filter := range cfg.ProjectFilters { + + if strings.Contains(strings.ToLower(project.ID), strings.ToLower(filter)) && filter != "" { + + l.Debug.Printf("[COLLECTION] The Project [ %v ] matches filter [ %v ] and won't be further processed.", project.ID, filter) + + continue allProjectsLoop + + } + + } + + // Filter by project name: + for _, filter := range cfg.NameFilters { + + if strings.Contains(strings.ToLower(project.Name), strings.ToLower(filter)) && filter != "" { + + l.Debug.Printf("[COLLECTION] The Project [ %v ] matches filter [ %v ] and won't be further processed.", project.Name, filter) + + continue allProjectsLoop + + } + + } + + pager := floatingips.List(networkClient, opts) + + e = pager.EachPage(func(page pagination.Page) (bool, error) { + + ipList, e := floatingips.ExtractFloatingIPs(page) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error processing the lists of active resources. Error: %+v\n", e) + + return false, e + + } + + apiCount += len(ipList) + + for _, ip := range ipList { + + // "ip" will be IP.IP + l.Trace.Printf("[COLLECTION] Found floating IP [ %v ] with ID [ %v ]. Parameters: Status [ %v ], Fixed IP [ %v ] and Floating Network ID [ %v ].\n", + ip.FloatingIP, ip.ID, ip.Status, ip.FixedIP, ip.FloatingNetworkID) + + // Here comes the transformation of the information retrieved into either + md := make(datamodels.JSONdb) + md["region"] = cfg.OpenStack.Region + md["floatingnetworkid"] = ip.FloatingNetworkID + + evTime := int64(time.Now().Unix()) + evLast := getStatus(ip.Status) + + // events or usage reports to be sent. + event := eeModels.Event{ + Account: project.ID, + EventTime: &evTime, + LastEvent: &evLast, + MetaData: md, + Region: cfg.OpenStack.Region, + ResourceID: ip.ID, + ResourceName: ip.FloatingIP, + ResourceType: "floatingip", + } + + report(event) + + //if this object exists in remote list then lets remove it + for i, object := range remotelist { + + if strings.Compare(object.Account, project.ID) == 0 && + strings.Compare(object.ResourceID, ip.ID) == 0 && + strings.Compare(object.ResourceName, ip.FloatingIP) == 0 { + + l.Debug.Printf("[COLLECTION] Event send cleaned from the processing list..\n") + + remotelist = append(remotelist[:i], remotelist[i+1:]...) + + break + + } + + } + + } + + return true, nil + + }) + + } + + l.Trace.Printf("[COLLECTION] (AFTER) Remaining count of floating IPs at remote which were left unprocessed [ %v ].\n", len(remotelist)) + + //now for all remaining servers send terminated status + for _, object := range remotelist { + + l.Debug.Printf("[COLLECTION] Sending termination for zombie data in the system..\n") + + evTime := int64(time.Now().Unix()) + evLast := getStatus("terminated") + + // events or usage reports to be sent. + event := eeModels.Event{ + Account: object.Account, + EventTime: &evTime, + LastEvent: &evLast, + MetaData: object.MetaData, + Region: cfg.OpenStack.Region, + ResourceID: object.ResourceID, + ResourceName: object.ResourceName, + ResourceType: "floatingip", + } + + report(event) + + } + + metricCount.With(prometheus.Labels{"type": "Total IPs reported by OS API"}).Set(float64(apiCount)) + + metricCount.With(prometheus.Labels{"type": "Total IPs from EventEngine"}).Set(float64(eeCount)) + + metricCount.With(prometheus.Labels{"type": "Total IPs forcefully TERMINATED"}).Set(float64(len(remotelist))) + + metricTime.With(prometheus.Labels{"type": "Collection Processing Time"}).Set(float64(time.Now().UnixNano()-collectionStart) / float64(time.Millisecond)) + + l.Warning.Printf("[COLLECTION] Completed.\n - OS Report: %v\n - EE Report: %v\n - Forced Termination: %v\n - Processing Time: %v[ms]\n", apiCount, eeCount, len(remotelist), float64(time.Now().UnixNano()-collectionStart)/float64(time.Millisecond)) + + l.Trace.Printf("[COLLECTION] The collection process has been finished.\n") + + return + +} + +// getStatus job is to normalize the event state returned by the collectors. +// Parameters: +// - state: string returned by the system. +// Returns: +// - status: normalized state to be returned. +func getStatus(state string) (status string) { + + switch strings.ToUpper(state) { + + case "ACTIVE": + + status = "active" + + case "ATTACHING": + + status = "active" + + case "AVAILABLE": + + status = "active" + + case "BUILD": + + status = "inactive" + + case "CREATING": + + status = "active" + + case "DELETED": + + status = "terminated" + + case "DELETING": + + status = "terminated" + + case "DETACHING": + + status = "active" + + case "DOWN": + + status = "inactive" + + case "ERROR": + + status = "error" + + case "ERROR_DELETING": + + status = "error" + + case "EXTENDING": + + status = "inactive" + + case "HARD_DELETED": + + status = "terminated" + + case "IN-USE": + + status = "active" + + case "MAINTENANCE": + + status = "active" + + case "PAUSED": + + status = "inactive" + + case "RESCUED": + + status = "active" + + case "RESIZE": + + status = "active" + + case "RESIZED": + + status = "active" + + case "RESERVED": + + status = "active" + + case "RETYPING": + + status = "inactive" + + case "SHUTOFF": + + status = "inactive" + + case "SOFT_DELETED": + + status = "terminated" + + case "STOPPED": + + status = "inactive" + + case "SUSPENDED": + + status = "inactive" + + case "TERMINATED": + + status = "terminated" + + case "VERIFY_RESIZE": + + status = "active" + + } + + l.Trace.Printf("[REPORT] State received from the system [ %v ] normalized to [ %v ]", state, status) + + return status + +} diff --git a/cyclops-collectors/network-collector/collector/config.go b/cyclops-collectors/network-collector/collector/config.go new file mode 100644 index 0000000..b31a94d --- /dev/null +++ b/cyclops-collectors/network-collector/collector/config.go @@ -0,0 +1,246 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool + Key string + Place string + Token string +} + +type configuration struct { + APIKey apiKey + General generalConfig + Heappe heappeConfig + Kafka kafkaConfig + Keycloak keycloakConfig + Lieutenant lieutenantConfig + OpenStack openStackConfig + Prometheus prometheusConfig + RGW rgwConfig + NameFilters []string + ProjectFilters []string + Services map[string]string +} + +type generalConfig struct { + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ObjectsPeriodicity int + Periodicity int + PrometheusPeriodicity int +} + +type heappeConfig struct { + Username string + Password string + GroupResourceUsageReportURI string + AuthenticateUserPasswordURI string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TLSEnabled bool + TopicUDR string + TopicEEngine string +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type lieutenantConfig struct { + Host string + Token string +} + +type openStackConfig struct { + Domain string + Keystone string + Password string + Project string + Region string + User string +} + +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +type rgwConfig struct { + AccessKeyID string + AdminPath string + Region string + SecretAccessKey string + ServerURL string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.Heappe.Username = masked(c.Heappe.Username, 4) + cfgCopy.Heappe.Password = masked(c.Heappe.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + cfgCopy.Lieutenant.Token = masked(c.Lieutenant.Token, 4) + cfgCopy.OpenStack.Password = masked(c.OpenStack.Password, 4) + cfgCopy.RGW.AccessKeyID = masked(c.RGW.AccessKeyID, 4) + cfgCopy.RGW.SecretAccessKey = masked(c.RGW.SecretAccessKey, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + General: generalConfig{ + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ObjectsPeriodicity: viper.GetInt("general.objectsperiodicity"), + Periodicity: viper.GetInt("general.periodicity"), + PrometheusPeriodicity: viper.GetInt("general.prometheusperiodicity"), + }, + + Heappe: heappeConfig{ + Username: viper.GetString("heappe.username"), + Password: viper.GetString("heappe.password"), + GroupResourceUsageReportURI: viper.GetString("heappe.groupResourceUsageReportUri"), + AuthenticateUserPasswordURI: viper.GetString("heappe.authenticateUserPasswordUri"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + TopicUDR: viper.GetString("kafka.topicudr"), + TopicEEngine: viper.GetString("kafka.topiceengine"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + Lieutenant: lieutenantConfig{ + Host: viper.GetString("lieutenant.host"), + Token: viper.GetString("lieutenant.token"), + }, + + OpenStack: openStackConfig{ + Domain: viper.GetString("openstack.domain"), + Keystone: viper.GetString("openstack.keystone"), + Password: viper.GetString("openstack.password"), + Project: viper.GetString("openstack.project"), + Region: viper.GetString("openstack.region"), + User: viper.GetString("openstack.user"), + }, + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + + RGW: rgwConfig{ + AccessKeyID: viper.GetString("rgw.accesskey"), + AdminPath: viper.GetString("rgw.adminpath"), + Region: viper.GetString("rgw.region"), + SecretAccessKey: viper.GetString("rgw.secretaccesskey"), + ServerURL: viper.GetString("rgw.serverurl"), + }, + + NameFilters: viper.GetStringSlice("events.namefilters"), + ProjectFilters: viper.GetStringSlice("events.projectfilters"), + Services: viper.GetStringMapString("services"), + } + + return + +} diff --git a/cyclops-collectors/network-collector/collector/kafka.go b/cyclops-collectors/network-collector/collector/kafka.go new file mode 100644 index 0000000..b265a2a --- /dev/null +++ b/cyclops-collectors/network-collector/collector/kafka.go @@ -0,0 +1,137 @@ +package main + +import ( + "context" + "crypto/tls" + "encoding/json" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/segmentio/kafka-go" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaHandlerConf struct { + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + channel chan interface{} +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.out != nil { + + for _, p := range kH.out { + + go kafkaSender(p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Go Channel Problems"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Kafka Stream Problems"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "OK", "reason": "Object sent"}).Inc() + + } + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "JSON Marshalling"}).Inc() + + } + + return + + }() + + } + +} diff --git a/cyclops-collectors/network-collector/collector/main.go b/cyclops-collectors/network-collector/collector/main.go new file mode 100644 index 0000000..e00cb47 --- /dev/null +++ b/cyclops-collectors/network-collector/collector/main.go @@ -0,0 +1,188 @@ +package main + +import ( + "flag" + "fmt" + "net/url" + "os" + "reflect" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/spf13/viper" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + eeClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + version string + cfg configuration + pipeU chan interface{} + pipeE chan interface{} + reportClient *eeClient.EventEngineManagementAPI + zombiesClient *cusClient.CustomerDatabaseManagement +) + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Returns: +// - ch: a interface{} channel to be able to send things through the kafka topic +// generated. +func kafkaStart() (chUDR, chEvents chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + chUDR = make(chan interface{}, 1000) + chEvents = make(chan interface{}, 1000) + + handler := kafkaHandlerConf{ + out: []kafkaPackage{ + { + topic: cfg.Kafka.TopicUDR, + channel: chUDR, + }, + { + topic: cfg.Kafka.TopicEEngine, + channel: chEvents, + }, + }, + } + + kafkaHandler(handler) + + return + +} + +// report handles the process of sending the event or usage to the respective +// service. +// Parameters: +// - object: an interface{} reference with the event/usage to be sent. +func report(object interface{}) { + + l.Trace.Printf("[REPORT] The reporting process has been started.\n") + + if reflect.TypeOf(object) == reflect.TypeOf(udrModels.Usage{}) { + + l.Trace.Printf("[REPORT] UDR Object detected. Sending through kafka.\n") + + pipeU <- object + + return + + } + + if reflect.TypeOf(object) == reflect.TypeOf(eeModels.Event{}) { + + l.Trace.Printf("[REPORT] Event Object detected. Sending through kafka.\n") + + pipeE <- object + + return + + } + + fail := "the provided object doesn't belong to UDR or EE models" + + l.Warning.Printf("[REPORT] Something went wrong while processing the object, check with the administrator. Error: %v.\n", fail) + + return + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: Collector-TYPE -conf=/path/to/configuration/file\n") + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %s\nCorrect usage: Collector-TYPE -conf=/path/to/configuration/file\n", err) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs Collector TYPE version %v initialized\n", version) + + dumpConfig(cfg) + + // Let's start the HTTP Server and Gauges for Prometheus + prometheusStart() + +} + +func main() { + + // If needed here is the initialization for the kafka sender: + pipeU, pipeE = kafkaStart() + + // Here we start the client instantiation to send reports to the EventsEngine. + eeConfig := eeClient.Config{ + URL: &url.URL{ + Host: cfg.Services["eventsengine"], + Path: eeClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + reportClient = eeClient.New(eeConfig) + + // Here we start the client instantiation to get the canceled customers to check for zombies. + cusConfig := cusClient.Config{ + URL: &url.URL{ + Host: cfg.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + zombiesClient = cusClient.New(cusConfig) + + // Let's lunch the first collection process.. + go collect() + + // cfg.General.Periodicity should be changed to cfg.General.ObjectPeriodicity + // in the case you need the long (8h) periodicity. + for range time.NewTicker(time.Duration(cfg.General.Periodicity) * time.Minute).C { + + go collect() + + } + +} diff --git a/cyclops-collectors/network-collector/collector/metrics.go b/cyclops-collectors/network-collector/collector/metrics.go new file mode 100644 index 0000000..4f7d9ec --- /dev/null +++ b/cyclops-collectors/network-collector/collector/metrics.go @@ -0,0 +1,95 @@ +package main + +import ( + "log" + "net/http" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricReporting *prometheus.GaugeVec + metricCollection *prometheus.GaugeVec + metricTime *prometheus.GaugeVec + metricCount *prometheus.GaugeVec +) + +func prometheusStart() { + + reg := prometheus.NewPedanticRegistry() + + metricReporting = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "kafka_send_state", + Help: "Reporting information and Kafka topics usage", + }, + []string{ + "reason", + "state", + "topic", + }, + ) + + metricCollection = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "Collection", + Help: "Collection information and usages data", + }, + []string{ + "account", + "event", + "reason", + "state", + "type", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "collection_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + metricCount = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: objects + "_count", + Help: "Different VM Counts", + }, + []string{ + "type", + }, + ) + + reg.MustRegister(metricReporting, metricCollection, metricTime, metricCount) + //prometheus.MustRegister(metricReporting, metricCollection) + + l.Trace.Printf("[Prometheus] Starting to serve the metrics.\n") + + go func() { + + if cfg.Prometheus.MetricsExport { + + //http.Handle(cfg.Prometheus.MetricsRoute, promhttp.Handler()) + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) + + go log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + } + + }() + +} diff --git a/cyclops-collectors/network-collector/go.mod b/cyclops-collectors/network-collector/go.mod new file mode 100644 index 0000000..584f71c --- /dev/null +++ b/cyclops-collectors/network-collector/go.mod @@ -0,0 +1,23 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/cyclops-collectors/network-collector + +go 1.13 + +require ( + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/swag v0.19.15 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/gophercloud/gophercloud v0.23.0 + github.com/magiconair/properties v1.8.5 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/segmentio/kafka-go v0.4.23 + github.com/spf13/afero v1.6.0 // indirect + github.com/spf13/viper v1.9.0 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1 // indirect +) diff --git a/cyclops-collectors/network-collector/run/cert.crt b/cyclops-collectors/network-collector/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/network-collector/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/cyclops-collectors/network-collector/run/config.toml b/cyclops-collectors/network-collector/run/config.toml new file mode 100644 index 0000000..17d47d4 --- /dev/null +++ b/cyclops-collectors/network-collector/run/config.toml @@ -0,0 +1,93 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# collector! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[EVENTS] +Filters = [ "filter1", "filter2", "filter3" ] + +[GENERAL] +LogFile = "" +LogToConsole = true +# loglevel values can be one of the following: TRACE, DEBUG, INFO, WARNING, ERROR +LogLevel = "TRACE" +ObjectsPeriodicity = 480 +Periodicity = 15 +PrometheusPeriodicity = 60 + +[HEAPPE] +Username = "" +Password = "" +GroupResourceUsageReportUri = "" +AuthenticateUserPasswordUri = "" + +[KAFKA] +Brokers = [ "broker-1-IP:broker-1-PORT", "broker-2-IP:broker-2-PORT", "broker-3-IP:broker-3-PORT" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMax = 10e6 +SizeMin = 10e3 +TLSEnabled = false +TopicEEngine = "Events" +TopicUDR = "UDR" + +[KEYCLOAK] +ClientID = "SERVICE" +ClientSecret = "00000000-0000-0000-0000-00000000" +Enabled = true +Host = "0.0.0.0" +Port = 8080 +Realm = "Development" +RedirectURL = "" +UseHttp = true + +[LIEUTENANT] +Host = "lieutenant:4010" +Token = "" + +[OPENSTACK] +Domain = "" +Keystone = "" +Password = "" +Project = "" +Region = "" +User = "" + +[PROMETHEUS] +Host = "prometheus:9000" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + +[RGW] +AccessKey = "" +AdminPath = "" +Region = "" +SecretAccessKey = "" +ServerURL = "" + +[SERVICES] +CustomerDB = "localhost:8400" +EventsEngine = "localhost:8500" diff --git a/cyclops-collectors/network-collector/run/docker-compose.yml b/cyclops-collectors/network-collector/run/docker-compose.yml new file mode 100644 index 0000000..152f08c --- /dev/null +++ b/cyclops-collectors/network-collector/run/docker-compose.yml @@ -0,0 +1,17 @@ +version: '3' + +services: + + collectors: + environment: + WAIT_AFTER_HOSTS: 30 + image: network-collector:latest + networks: + - collectorsnet + restart: always + volumes: + - ${PWD}/config.toml:/config.toml + +networks: + collectorsnet: + driver: bridge diff --git a/cyclops-collectors/network-collector/run/key.key b/cyclops-collectors/network-collector/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/network-collector/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/cyclops-collectors/objects-collector/README.md b/cyclops-collectors/objects-collector/README.md new file mode 100644 index 0000000..5510c9f --- /dev/null +++ b/cyclops-collectors/objects-collector/README.md @@ -0,0 +1,25 @@ +# OBJECTS COLLECTOR + +OpenStack Objects collector written in go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` diff --git a/cyclops-collectors/objects-collector/collector/collector.go b/cyclops-collectors/objects-collector/collector/collector.go new file mode 100644 index 0000000..0f53c15 --- /dev/null +++ b/cyclops-collectors/objects-collector/collector/collector.go @@ -0,0 +1,317 @@ +package main + +import ( + "context" + "encoding/hex" + "strings" + "time" + + rgw "github.com/myENA/radosgwadmin" + rcl "github.com/myENA/restclient" + "github.com/prometheus/client_golang/prometheus" + "github.com/remeh/sizedwaitgroup" + datamodels "gitlab.com/cyclops-utilities/datamodels" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + collector = "Objects" + objects = "object" + collectionStart int64 +) + +// collect handles the process of retrieving the information from the system. +func collect() { + + l.Trace.Printf("[COLLECTION] The collection process has been started.\n") + + collectionStart = time.Now().UnixNano() + + metricTime.With(prometheus.Labels{"type": "Collection Start Time"}).Set(float64(collectionStart)) + + // Here comes the logic to retrieve the information from the system. + rcfg := &rgw.Config{ + AdminPath: cfg.RGW.AdminPath, + AccessKeyID: cfg.RGW.AccessKeyID, + ClientConfig: rcl.ClientConfig{ + ClientTimeout: rcl.Duration(time.Second * 30), + }, + SecretAccessKey: cfg.RGW.SecretAccessKey, + ServerURL: cfg.RGW.ServerURL, + } + + a, e := rgw.NewAdminAPI(rcfg) + + if e != nil { + + l.Warning.Printf("[COLLECTION] Could not authenticate with RadosGW. Not obtaining data for this period. Error: %v\n", e.Error()) + + return + + } + + users, e := a.MListUsers(context.Background()) + + if e != nil { + + l.Warning.Printf("[COLLECTION] Error reading project lists from RGW. Not obtaining data for this period. Error: %v\n", e.Error()) + + return + + } + + apiCount := 0 + dropCount := 0 + + swg := sizedwaitgroup.New(8) + + // fmt.Printf("Users = %v\n", users) + for _, user := range users { + + // Goroutines start + swg.Add() + go func(u string) { + + defer swg.Done() + + // filter out users which are not Openstack projects + if filterOpenstackProject(u) { + + // get all buckets for given user + bucketList, e := a.BucketList(context.Background(), u) + + if e != nil { + + l.Warning.Printf("[COLLECTION] Error reading bucket list for user [ %v ] from RGW. Error: %v\n", u, e.Error()) + + } + + // l.Info.Printf("bucketlist = %v\n", bucketList) + + totalBuckets := len(bucketList) + aggregateBucketSize := float64(0.0) + + apiCount += len(bucketList) + + for _, b := range bucketList { + + bucketStats, e := a.BucketStats(context.Background(), u, b) + + if e != nil { + + l.Warning.Printf("[COLLECTION] Error reading bucket list for user [ %v ] from RGW. Error: %v\n", u, e.Error()) + + } + + if len(bucketStats) == 0 { + + l.Warning.Printf("[COLLECTION] The length of bucket stats = 0 for the bucket [ %v ]\n", b) + + } else { + + d := datamodels.JSONdb{ + "region": cfg.RGW.Region, + "bucket": b, + } + + // the Usage struct contains support for a number of different RGWs... + // RGWMain, RGWShadow and a couple of others; here we just take + // RGWMain as the base - if it's null, we don't publish anything to UDR + // RGWMain contains SizeKbActual and SizeKb - SizeKBActual is used here; + // this is the usage as perceived by the user, SizeKb is a bit larger with + // the delta dependent on the basic minimum object size allocation + if bucketStats[0].Usage.RGWMain != nil { + + usage := float64(bucketStats[0].Usage.RGWMain.SizeKb) + + if usage != 0 { + + // Here comes the transformation of the information retrieved into either + // events or usage reports to be sent. + usageReport := udrModels.Usage{ + Account: u, + Metadata: d, + ResourceType: "objectstorage", + Time: time.Now().Unix(), + Unit: "GB", + Usage: float64((usage / float64(1024)) / float64(1024)), + } + + report(usageReport) + + aggregateBucketSize += usageReport.Usage + + } + + } else { + + l.Warning.Printf("[COLLECTION] There's no information for RGWMain for the bucket [ %v ]. Ignoring...\n", b) + + dropCount++ + + } + } + } + + l.Info.Printf("[COLLECTION] Wrote data for user [ %v ]. AggregateBucketSize [ %v ] distributed over [ %v ] buckets.\n", u, aggregateBucketSize, totalBuckets) + + } + + }(user) + + } + + swg.Wait() + + metricCount.With(prometheus.Labels{"type": "Total Objects reported by OS API"}).Set(float64(apiCount)) + + metricCount.With(prometheus.Labels{"type": "Total Objects DROPPED due to missing information"}).Set(float64(dropCount)) + + metricTime.With(prometheus.Labels{"type": "Collection Processing Time"}).Set(float64(time.Now().UnixNano()-collectionStart) / float64(time.Millisecond)) + + l.Warning.Printf("[COLLECTION] Completed.\n OS Report: %v\n, Dropped: %v\n, Processing Time: %v[ms]\n", apiCount, dropCount, float64(time.Now().UnixNano()-collectionStart)/float64(time.Millisecond)) + + l.Trace.Printf("[COLLECTION] The collection process has been finished.\n") + + return + +} + +// filterOpenstackProject checks if the user name looks like an Openstack +// project. +// Parameters: +// - p: string representing the user. +// Returns: +// - a bool with the result of the check. +func filterOpenstackProject(p string) bool { + + _, e := hex.DecodeString(p) + + return (len(p) == 32) && (e == nil) +} + +// getStatus job is to normalize the event state returned by the collectors. +// Parameters: +// - state: string returned by the system. +// Returns: +// - status: normalized state to be returned. +func getStatus(state string) (status string) { + + switch strings.ToUpper(state) { + + case "ACTIVE": + + status = "active" + + case "ATTACHING": + + status = "active" + + case "AVAILABLE": + + status = "active" + + case "BUILD": + + status = "inactive" + + case "CREATING": + + status = "active" + + case "DELETED": + + status = "terminated" + + case "DELETING": + + status = "terminated" + + case "DETACHING": + + status = "active" + + case "DOWN": + + status = "inactive" + + case "ERROR": + + status = "error" + + case "ERROR_DELETING": + + status = "error" + + case "EXTENDING": + + status = "inactive" + + case "HARD_DELETED": + + status = "terminated" + + case "IN-USE": + + status = "active" + + case "MAINTENANCE": + + status = "active" + + case "PAUSED": + + status = "inactive" + + case "RESCUED": + + status = "active" + + case "RESIZE": + + status = "active" + + case "RESIZED": + + status = "active" + + case "RESERVED": + + status = "active" + + case "RETYPING": + + status = "inactive" + + case "SHUTOFF": + + status = "inactive" + + case "SOFT_DELETED": + + status = "terminated" + + case "STOPPED": + + status = "inactive" + + case "SUSPENDED": + + status = "inactive" + + case "TERMINATED": + + status = "terminated" + + case "VERIFY_RESIZE": + + status = "active" + + } + + l.Trace.Printf("[REPORT] State received from the system [ %v ] normalized to [ %v ]", state, status) + + return status + +} diff --git a/cyclops-collectors/objects-collector/collector/config.go b/cyclops-collectors/objects-collector/collector/config.go new file mode 100644 index 0000000..b31a94d --- /dev/null +++ b/cyclops-collectors/objects-collector/collector/config.go @@ -0,0 +1,246 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool + Key string + Place string + Token string +} + +type configuration struct { + APIKey apiKey + General generalConfig + Heappe heappeConfig + Kafka kafkaConfig + Keycloak keycloakConfig + Lieutenant lieutenantConfig + OpenStack openStackConfig + Prometheus prometheusConfig + RGW rgwConfig + NameFilters []string + ProjectFilters []string + Services map[string]string +} + +type generalConfig struct { + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ObjectsPeriodicity int + Periodicity int + PrometheusPeriodicity int +} + +type heappeConfig struct { + Username string + Password string + GroupResourceUsageReportURI string + AuthenticateUserPasswordURI string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TLSEnabled bool + TopicUDR string + TopicEEngine string +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type lieutenantConfig struct { + Host string + Token string +} + +type openStackConfig struct { + Domain string + Keystone string + Password string + Project string + Region string + User string +} + +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +type rgwConfig struct { + AccessKeyID string + AdminPath string + Region string + SecretAccessKey string + ServerURL string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.Heappe.Username = masked(c.Heappe.Username, 4) + cfgCopy.Heappe.Password = masked(c.Heappe.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + cfgCopy.Lieutenant.Token = masked(c.Lieutenant.Token, 4) + cfgCopy.OpenStack.Password = masked(c.OpenStack.Password, 4) + cfgCopy.RGW.AccessKeyID = masked(c.RGW.AccessKeyID, 4) + cfgCopy.RGW.SecretAccessKey = masked(c.RGW.SecretAccessKey, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + General: generalConfig{ + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ObjectsPeriodicity: viper.GetInt("general.objectsperiodicity"), + Periodicity: viper.GetInt("general.periodicity"), + PrometheusPeriodicity: viper.GetInt("general.prometheusperiodicity"), + }, + + Heappe: heappeConfig{ + Username: viper.GetString("heappe.username"), + Password: viper.GetString("heappe.password"), + GroupResourceUsageReportURI: viper.GetString("heappe.groupResourceUsageReportUri"), + AuthenticateUserPasswordURI: viper.GetString("heappe.authenticateUserPasswordUri"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + TopicUDR: viper.GetString("kafka.topicudr"), + TopicEEngine: viper.GetString("kafka.topiceengine"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + Lieutenant: lieutenantConfig{ + Host: viper.GetString("lieutenant.host"), + Token: viper.GetString("lieutenant.token"), + }, + + OpenStack: openStackConfig{ + Domain: viper.GetString("openstack.domain"), + Keystone: viper.GetString("openstack.keystone"), + Password: viper.GetString("openstack.password"), + Project: viper.GetString("openstack.project"), + Region: viper.GetString("openstack.region"), + User: viper.GetString("openstack.user"), + }, + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + + RGW: rgwConfig{ + AccessKeyID: viper.GetString("rgw.accesskey"), + AdminPath: viper.GetString("rgw.adminpath"), + Region: viper.GetString("rgw.region"), + SecretAccessKey: viper.GetString("rgw.secretaccesskey"), + ServerURL: viper.GetString("rgw.serverurl"), + }, + + NameFilters: viper.GetStringSlice("events.namefilters"), + ProjectFilters: viper.GetStringSlice("events.projectfilters"), + Services: viper.GetStringMapString("services"), + } + + return + +} diff --git a/cyclops-collectors/objects-collector/collector/kafka.go b/cyclops-collectors/objects-collector/collector/kafka.go new file mode 100644 index 0000000..b265a2a --- /dev/null +++ b/cyclops-collectors/objects-collector/collector/kafka.go @@ -0,0 +1,137 @@ +package main + +import ( + "context" + "crypto/tls" + "encoding/json" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/segmentio/kafka-go" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaHandlerConf struct { + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + channel chan interface{} +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.out != nil { + + for _, p := range kH.out { + + go kafkaSender(p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Go Channel Problems"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Kafka Stream Problems"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "OK", "reason": "Object sent"}).Inc() + + } + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "JSON Marshalling"}).Inc() + + } + + return + + }() + + } + +} diff --git a/cyclops-collectors/objects-collector/collector/main.go b/cyclops-collectors/objects-collector/collector/main.go new file mode 100644 index 0000000..e00cb47 --- /dev/null +++ b/cyclops-collectors/objects-collector/collector/main.go @@ -0,0 +1,188 @@ +package main + +import ( + "flag" + "fmt" + "net/url" + "os" + "reflect" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/spf13/viper" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + eeClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + version string + cfg configuration + pipeU chan interface{} + pipeE chan interface{} + reportClient *eeClient.EventEngineManagementAPI + zombiesClient *cusClient.CustomerDatabaseManagement +) + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Returns: +// - ch: a interface{} channel to be able to send things through the kafka topic +// generated. +func kafkaStart() (chUDR, chEvents chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + chUDR = make(chan interface{}, 1000) + chEvents = make(chan interface{}, 1000) + + handler := kafkaHandlerConf{ + out: []kafkaPackage{ + { + topic: cfg.Kafka.TopicUDR, + channel: chUDR, + }, + { + topic: cfg.Kafka.TopicEEngine, + channel: chEvents, + }, + }, + } + + kafkaHandler(handler) + + return + +} + +// report handles the process of sending the event or usage to the respective +// service. +// Parameters: +// - object: an interface{} reference with the event/usage to be sent. +func report(object interface{}) { + + l.Trace.Printf("[REPORT] The reporting process has been started.\n") + + if reflect.TypeOf(object) == reflect.TypeOf(udrModels.Usage{}) { + + l.Trace.Printf("[REPORT] UDR Object detected. Sending through kafka.\n") + + pipeU <- object + + return + + } + + if reflect.TypeOf(object) == reflect.TypeOf(eeModels.Event{}) { + + l.Trace.Printf("[REPORT] Event Object detected. Sending through kafka.\n") + + pipeE <- object + + return + + } + + fail := "the provided object doesn't belong to UDR or EE models" + + l.Warning.Printf("[REPORT] Something went wrong while processing the object, check with the administrator. Error: %v.\n", fail) + + return + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: Collector-TYPE -conf=/path/to/configuration/file\n") + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %s\nCorrect usage: Collector-TYPE -conf=/path/to/configuration/file\n", err) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs Collector TYPE version %v initialized\n", version) + + dumpConfig(cfg) + + // Let's start the HTTP Server and Gauges for Prometheus + prometheusStart() + +} + +func main() { + + // If needed here is the initialization for the kafka sender: + pipeU, pipeE = kafkaStart() + + // Here we start the client instantiation to send reports to the EventsEngine. + eeConfig := eeClient.Config{ + URL: &url.URL{ + Host: cfg.Services["eventsengine"], + Path: eeClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + reportClient = eeClient.New(eeConfig) + + // Here we start the client instantiation to get the canceled customers to check for zombies. + cusConfig := cusClient.Config{ + URL: &url.URL{ + Host: cfg.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + zombiesClient = cusClient.New(cusConfig) + + // Let's lunch the first collection process.. + go collect() + + // cfg.General.Periodicity should be changed to cfg.General.ObjectPeriodicity + // in the case you need the long (8h) periodicity. + for range time.NewTicker(time.Duration(cfg.General.Periodicity) * time.Minute).C { + + go collect() + + } + +} diff --git a/cyclops-collectors/objects-collector/collector/metrics.go b/cyclops-collectors/objects-collector/collector/metrics.go new file mode 100644 index 0000000..4f7d9ec --- /dev/null +++ b/cyclops-collectors/objects-collector/collector/metrics.go @@ -0,0 +1,95 @@ +package main + +import ( + "log" + "net/http" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricReporting *prometheus.GaugeVec + metricCollection *prometheus.GaugeVec + metricTime *prometheus.GaugeVec + metricCount *prometheus.GaugeVec +) + +func prometheusStart() { + + reg := prometheus.NewPedanticRegistry() + + metricReporting = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "kafka_send_state", + Help: "Reporting information and Kafka topics usage", + }, + []string{ + "reason", + "state", + "topic", + }, + ) + + metricCollection = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "Collection", + Help: "Collection information and usages data", + }, + []string{ + "account", + "event", + "reason", + "state", + "type", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "collection_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + metricCount = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: objects + "_count", + Help: "Different VM Counts", + }, + []string{ + "type", + }, + ) + + reg.MustRegister(metricReporting, metricCollection, metricTime, metricCount) + //prometheus.MustRegister(metricReporting, metricCollection) + + l.Trace.Printf("[Prometheus] Starting to serve the metrics.\n") + + go func() { + + if cfg.Prometheus.MetricsExport { + + //http.Handle(cfg.Prometheus.MetricsRoute, promhttp.Handler()) + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) + + go log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + } + + }() + +} diff --git a/cyclops-collectors/objects-collector/go.mod b/cyclops-collectors/objects-collector/go.mod new file mode 100644 index 0000000..671a553 --- /dev/null +++ b/cyclops-collectors/objects-collector/go.mod @@ -0,0 +1,35 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/cyclops-collectors/objects-collector + +go 1.13 + +require ( + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/strfmt v0.21.1 // indirect + github.com/go-playground/universal-translator v0.18.0 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/google/go-querystring v1.1.0 // indirect + github.com/leodido/go-urn v1.2.1 // indirect + github.com/magiconair/properties v1.8.5 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mitchellh/mapstructure v1.4.3 // indirect + github.com/myENA/radosgwadmin v0.1.0 + github.com/myENA/restclient v1.0.5 + github.com/prometheus/client_golang v1.11.0 + github.com/remeh/sizedwaitgroup v1.0.0 + github.com/segmentio/kafka-go v0.4.25 + github.com/smartystreets/go-aws-auth v0.0.0-20180515143844-0c1422d1fdb9 // indirect + github.com/spf13/afero v1.6.0 // indirect + github.com/spf13/viper v1.9.0 + github.com/spkg/bom v1.0.0 // indirect + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + go.mongodb.org/mongo-driver v1.8.0 // indirect + golang.org/x/net v0.0.0-20211201190559-0a0e4e1bb54c // indirect + golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 // indirect + gopkg.in/go-playground/validator.v9 v9.31.0 // indirect + gopkg.in/ini.v1 v1.66.1 // indirect +) diff --git a/cyclops-collectors/objects-collector/run/cert.crt b/cyclops-collectors/objects-collector/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/objects-collector/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/cyclops-collectors/objects-collector/run/config.toml b/cyclops-collectors/objects-collector/run/config.toml new file mode 100644 index 0000000..17d47d4 --- /dev/null +++ b/cyclops-collectors/objects-collector/run/config.toml @@ -0,0 +1,93 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# collector! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[EVENTS] +Filters = [ "filter1", "filter2", "filter3" ] + +[GENERAL] +LogFile = "" +LogToConsole = true +# loglevel values can be one of the following: TRACE, DEBUG, INFO, WARNING, ERROR +LogLevel = "TRACE" +ObjectsPeriodicity = 480 +Periodicity = 15 +PrometheusPeriodicity = 60 + +[HEAPPE] +Username = "" +Password = "" +GroupResourceUsageReportUri = "" +AuthenticateUserPasswordUri = "" + +[KAFKA] +Brokers = [ "broker-1-IP:broker-1-PORT", "broker-2-IP:broker-2-PORT", "broker-3-IP:broker-3-PORT" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMax = 10e6 +SizeMin = 10e3 +TLSEnabled = false +TopicEEngine = "Events" +TopicUDR = "UDR" + +[KEYCLOAK] +ClientID = "SERVICE" +ClientSecret = "00000000-0000-0000-0000-00000000" +Enabled = true +Host = "0.0.0.0" +Port = 8080 +Realm = "Development" +RedirectURL = "" +UseHttp = true + +[LIEUTENANT] +Host = "lieutenant:4010" +Token = "" + +[OPENSTACK] +Domain = "" +Keystone = "" +Password = "" +Project = "" +Region = "" +User = "" + +[PROMETHEUS] +Host = "prometheus:9000" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + +[RGW] +AccessKey = "" +AdminPath = "" +Region = "" +SecretAccessKey = "" +ServerURL = "" + +[SERVICES] +CustomerDB = "localhost:8400" +EventsEngine = "localhost:8500" diff --git a/cyclops-collectors/objects-collector/run/docker-compose.yml b/cyclops-collectors/objects-collector/run/docker-compose.yml new file mode 100644 index 0000000..f561cb1 --- /dev/null +++ b/cyclops-collectors/objects-collector/run/docker-compose.yml @@ -0,0 +1,17 @@ +version: '3' + +services: + + collectors: + environment: + WAIT_AFTER_HOSTS: 30 + image: objects-collector:latest + networks: + - collectorsnet + restart: always + volumes: + - ${PWD}/config.toml:/config.toml + +networks: + collectorsnet: + driver: bridge diff --git a/cyclops-collectors/objects-collector/run/key.key b/cyclops-collectors/objects-collector/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/objects-collector/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/cyclops-collectors/servers-collector/README.md b/cyclops-collectors/servers-collector/README.md new file mode 100644 index 0000000..6531bd2 --- /dev/null +++ b/cyclops-collectors/servers-collector/README.md @@ -0,0 +1,25 @@ +# SERVERS COLLECTOR + +OpenStack Servers/Instances collector written in go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` diff --git a/cyclops-collectors/servers-collector/collector/cache.go b/cyclops-collectors/servers-collector/collector/cache.go new file mode 100644 index 0000000..f6fbcb8 --- /dev/null +++ b/cyclops-collectors/servers-collector/collector/cache.go @@ -0,0 +1,189 @@ +package main + +import ( + "time" + + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors" + "github.com/gophercloud/gophercloud/openstack/compute/v2/images" + l "gitlab.com/cyclops-utilities/logging" +) + +type FlavorIDCacheData struct { + FlavorName string + LastRefreshed int64 +} + +type ImageIDCacheData struct { + ImageName string + OSFlavor string + LastRefreshed int64 +} + +var ( + FlavorCache map[string]FlavorIDCacheData + ImageCache map[string]ImageIDCacheData +) + +func getFromFlavorCache(client *gophercloud.ServiceClient, flavorid string) (flavorname string, e error) { + + var flavor *flavors.Flavor + + if FlavorCache[flavorid].LastRefreshed != 0 { + + //the cache entry exists + l.Trace.Printf("[CACHE] Flavor cache entry found for key: %v.\n", flavorid) + + if time.Now().Unix()-FlavorCache[flavorid].LastRefreshed > 86400 { + + //invalidate the entry and get a fresh one + l.Trace.Printf("[CACHE] Cache invalidation for key [ %v ], refreshing entry now.\n", flavorid) + + flavor, e = flavors.Get(client, flavorid).Extract() + + if e != nil { + + l.Warning.Printf("[CACHE] Error reading remote API response for flavor-id data. Error: %v\n", e) + + return + + } + + flavorname = flavor.Name + + FlavorCache[flavorid] = FlavorIDCacheData{ + flavor.Name, + time.Now().Unix(), + } + + l.Trace.Printf("[CACHE] Cache entry updated for key [ %v ]. New value returned.\n", flavorid) + + return + + } + + l.Trace.Printf("[CACHE] Cache entry value for key [ %v ] returned without refreshing.\n", flavorid) + + flavorname = FlavorCache[flavorid].FlavorName + + return + + } + + l.Trace.Printf("[CACHE] Cache entry miss for key: %v\n.", flavorid) + + flavor, e = flavors.Get(client, flavorid).Extract() + + if e != nil { + + l.Warning.Printf("[CACHE] Error reading remote API response for flavor-id data. Error: %v ", e) + + return + + } + + flavorname = flavor.Name + + l.Trace.Printf("[CACHE] Going to add a new cache entry added for key: %v\n", flavorid) + + FlavorCache[flavorid] = FlavorIDCacheData{ + flavor.Name, + time.Now().Unix(), + } + + l.Trace.Printf("[CACHE] Cache entry added for key [ %v ]. New value returned.\n", flavorid) + + return + +} + +func getFromImageCache(client *gophercloud.ServiceClient, imageid string) (imagename string, osflavor string, e error) { + + var image *images.Image + + if ImageCache[imageid].LastRefreshed != 0 { + + //the cache entry exists + l.Trace.Printf("[CACHE] Image cache entry found for image key: %v.\n", imageid) + + if time.Now().Unix()-ImageCache[imageid].LastRefreshed > 86400 { + + //invalidate the entry and get a fresh one + l.Trace.Printf("[CACHE] Cache invalidation for image key [ %v ], refreshing entry now.\n", imageid) + + image, e = images.Get(client, imageid).Extract() + + if e != nil { + + l.Warning.Printf("[CACHE] Error reading remote API response for image data. Error: %v.\n", e) + + return + + } + + imagename = image.Name + + osflavor_test, exists := image.Metadata["os_flavor"] //image operating system flavor + + if exists { + + osflavor = osflavor_test.(string) + + } + + ImageCache[imageid] = ImageIDCacheData{ + image.Name, + osflavor, + time.Now().Unix(), + } + + l.Trace.Printf("[CACHE] Cache entry updated for image key [ %v ]. New value returned.\n", imageid) + + return + + } + + l.Trace.Printf("[CACHE] Cache entry value for image key [ %v ] returned without refreshing.\n", imageid) + + imagename = ImageCache[imageid].ImageName + osflavor = ImageCache[imageid].OSFlavor + + return + + } + + l.Trace.Printf("[CACHE] Cache entry miss for image key: %v.\n", imageid) + + image, e = images.Get(client, imageid).Extract() + + if e != nil { + + l.Warning.Printf("[CACHE] Error reading remote API response for image data. Error: %v.\n", e) + + return + + } + + imagename = image.Name + + osflavor_test, exists := image.Metadata["os_flavor"] //image operating system flavor + + if exists { + + osflavor = osflavor_test.(string) + + } + + l.Trace.Printf("[CACHE] Going to add a new cache entry added for image key: " + imageid) + + ImageCache[imageid] = ImageIDCacheData{ + image.Name, + osflavor, + time.Now().Unix(), + } + + l.Trace.Printf("[CACHE] Cache entry added for image key: " + imageid + ". New value returned.") + + return + +} diff --git a/cyclops-collectors/servers-collector/collector/collector.go b/cyclops-collectors/servers-collector/collector/collector.go new file mode 100644 index 0000000..4138831 --- /dev/null +++ b/cyclops-collectors/servers-collector/collector/collector.go @@ -0,0 +1,480 @@ +package main + +import ( + "context" + "os" + "strings" + "time" + + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack" + "github.com/gophercloud/gophercloud/openstack/compute/v2/servers" + "github.com/gophercloud/gophercloud/pagination" + "github.com/prometheus/client_golang/prometheus" + datamodels "gitlab.com/cyclops-utilities/datamodels" + eeEvent "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/event_management" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + collector = "Servers" + objects = "vm" + collectionStart int64 + vmCount int + terminatedCount int + dropCount int + remotelist []*eeModels.MinimalState + client *gophercloud.ServiceClient +) + +// collect handles the process of retrieving the information from the system. +func collect() { + + l.Trace.Printf("[COLLECTION] The collection process has been started.\n") + + collectionStart = time.Now().UnixNano() + + metricTime.With(prometheus.Labels{"type": "Collection Start Time"}).Set(float64(collectionStart)) + + // Here comes the logic to retrieve the information from the system. + opts := gophercloud.AuthOptions{ + DomainName: cfg.OpenStack.Domain, + IdentityEndpoint: cfg.OpenStack.Keystone, + Password: cfg.OpenStack.Password, + Username: cfg.OpenStack.User, + } + + if len(cfg.OpenStack.Project) > 0 { + + opts.TenantName = cfg.OpenStack.Project + + } + + provider, e := openstack.AuthenticatedClient(opts) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error authenticating against OpenStack. Error: %v", e) + + os.Exit(1) + + } + + client, e = openstack.NewComputeV2(provider, gophercloud.EndpointOpts{ + Region: cfg.OpenStack.Region, + }) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error creating compute collector client. Error: %v", e) + + os.Exit(1) + + } + + serveropts := servers.ListOpts{ + AllTenants: true, //set this to true to list VMs from all tenants if policy allows it + } + + l.Trace.Printf("[COLLECTION] Querying events engine service for list of known and not terminated servers") + + resourceType := "server" + eeParams := eeEvent.NewListStatesParams().WithResource(&resourceType).WithRegion(&cfg.OpenStack.Region) + + ctx, _ := context.WithTimeout(context.Background(), 300*time.Second) + r, e := reportClient.EventManagement.ListStates(ctx, eeParams) + + // Clears the remotelist between runs + remotelist = nil + + if e != nil { + + l.Warning.Printf("[COLLECTION] Something went wrong while retrieving the usage from the system, check with the administrator. Error: %v.\n", e) + + } else { + + remotelist = r.Payload + + } + + metricCount.With(prometheus.Labels{"type": "Total VMs from EventEngine"}).Set(float64(len(remotelist))) + + l.Trace.Printf("[COLLECTION] (BEFORE) Existing count of servers at remote [ %v ].\n", len(remotelist)) + + eeCount := len(remotelist) + + pager := servers.List(client, serveropts) + + vmCount = 0 + + e = pager.EachPage(extractPage) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error processing the lists of active resources. Error: %v\n", e) + + os.Exit(1) + + } + + metricCount.With(prometheus.Labels{"type": "Total VMs reported by OS API"}).Set(float64(vmCount)) + + metricCount.With(prometheus.Labels{"type": "Total VMs reported by OS API (to terminated state)"}).Set(float64(terminatedCount)) + + metricCount.With(prometheus.Labels{"type": "Total VMs DROPPED due to unknown flavor"}).Set(float64(dropCount)) + + l.Trace.Printf("[COLLECTION] (AFTER) Remaining count of servers at remote which were left unprocessed [ %v ].\n", len(remotelist)) + + //now for all remaining servers send terminated status + for _, object := range remotelist { + + l.Trace.Printf("[COLLECTION] Sending terminated event for server [ %v ] for project [ %v ] with ID [ %v ].\n", object.ResourceID, object.ResourceName, object.Account) + + evTime := int64(time.Now().Unix()) + evLast := getStatus("terminated") + + // events reports to be sent. + event := eeModels.Event{ + Account: object.Account, + EventTime: &evTime, + LastEvent: &evLast, + MetaData: object.MetaData, + Region: cfg.OpenStack.Region, + ResourceID: object.ResourceID, + ResourceName: object.ResourceName, + ResourceType: "server", + } + + report(event) + + } + + metricCount.With(prometheus.Labels{"type": "Total VMs forcefully TERMINATED"}).Set(float64(len(remotelist))) + + metricTime.With(prometheus.Labels{"type": "Collection Processing Time"}).Set(float64(time.Now().UnixNano()-collectionStart) / float64(time.Millisecond)) + + l.Warning.Printf("[COLLECTION] Completed.\n - OS Report: %v\n - EE Report: %v\n - Droped: %v\n - OS Terminated: %v\n - Forced Termination: %v\n - Processing Time: %v[ms]\n", vmCount, eeCount, dropCount, terminatedCount, len(remotelist), float64(time.Now().UnixNano()-collectionStart)/float64(time.Millisecond)) + + l.Trace.Printf("[COLLECTION] The collection process has been finished.\n") + + return + +} + +// extractPage is the handler function invoked to process each page collected +// from the server list. +// Parameters: +// - page: Pagination.Page reference of the page to be processed. +// Returns: +// - ok: a bool to mark the state of the processing. +// - e: an error reference raised in case of something goes wrong. +func extractPage(page pagination.Page) (ok bool, e error) { + + var serverList []servers.Server + + serverList, e = servers.ExtractServers(page) + + if e != nil { + + return + + } + +allProjectsLoop: + for _, s := range serverList { + + // Filter by project id: + for _, filter := range cfg.ProjectFilters { + + if strings.Contains(s.TenantID, filter) && filter != "" { + + l.Debug.Printf("[COLLECTION] The Project [ %v ] matches filter [ %v ] and won't be further processed.", s.TenantID, filter) + + continue allProjectsLoop + + } + + } + + // Filter by project name: + for _, filter := range cfg.NameFilters { + + if strings.Contains(strings.ToLower(s.Name), strings.ToLower(filter)) && filter != "" { + + l.Debug.Printf("[COLLECTION] The Project [ %v ] matches filter [ %v ] and won't be further processed.", s.Name, filter) + + continue allProjectsLoop + + } + + } + + vmCount++ + + // "s" will be a servers.Server + var imageid, flavorid, imagename, imageosflavor, flavorname string + + for k, val := range s.Image { + + switch v := val.(type) { + + case string: + + if strings.Compare(k, "id") == 0 { + + imageid = v + + } + + } + + } + + for k, val := range s.Flavor { + + switch v := val.(type) { + + case string: + + if strings.Compare(k, "id") == 0 { + + flavorid = v + + } + + } + + } + + l.Trace.Printf("%+v, %v", client, imageid) + + imagename, imageosflavor, e := getFromImageCache(client, imageid) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error while getting the image id [ %+v ]. Error: %v\n", imageid, e) + + } + + flavorname, e = getFromFlavorCache(client, flavorid) + + if e != nil { + + l.Error.Printf("[COLLECTION] Error while getting the flavor id [ %+v ]. Error: %v\n", flavorid, e) + + } + + if len(flavorname) == 0 { + + l.Warning.Printf("[COLLECTION] Found VM - Name:[%s], TenantID:[%s], Status:[%s], ID:[%s], ImageID:[%s], ImageName:[%s], ImageOSFlavor:[%s], FlavorId:[%s], FlavorName:[%s] :: with missing FlavorName, skipping record!", + s.Name, s.TenantID, s.Status, s.ID, imageid, imagename, imageosflavor, flavorid, flavorname) + + dropCount++ + + continue + + } + + l.Info.Printf("[COLLECTION] Found VM - Name:[%s], TenantID:[%s], Status:[%s], ID:[%s], ImageID:[%s], ImageName:[%s], ImageOSFlavor:[%s], FlavorId:[%s], FlavorName:[%s]", + s.Name, s.TenantID, s.Status, s.ID, imageid, imagename, imageosflavor, flavorid, flavorname) + + // Potential problem with these filters are if clients create their + // VMs with the filter strings those will not be billed. + // It will be better to actually filter out all resources within a given + // tenant, so if rally or tempest testrun create resources exclusively + // belonging to a specific tenant then that tenant can be filtered out. + // TODO: TBD with SWITCH! + + // Here comes the transformation of the information retrieved into either + metadata := make(datamodels.JSONdb) + metadata["imageid"] = imageid + metadata["imagename"] = imagename + metadata["imageosflavor"] = imageosflavor + metadata["flavorid"] = flavorid + metadata["flavorname"] = flavorname + metadata["region"] = cfg.OpenStack.Region + + // TODO: MAke more generic and customizable via config file + if value, exists := s.Metadata["schedule_frequency"]; exists && value == "never" { + + metadata["PlanOverride"] = true + + } + + evTime := int64(time.Now().Unix()) + evLast := getStatus(s.Status) + + if evLast == "terminated" { + + terminatedCount++ + + } + + // events reports to be sent. + event := eeModels.Event{ + Account: s.TenantID, + EventTime: &evTime, + LastEvent: &evLast, + MetaData: metadata, + Region: cfg.OpenStack.Region, + ResourceID: s.ID, + ResourceName: s.Name, + ResourceType: "server", + } + + report(event) + + //if this object exists in remote list then lets remove it + for i, object := range remotelist { + + if strings.Compare(object.Account, s.TenantID) == 0 && + strings.Compare(object.ResourceID, s.ID) == 0 && + strings.Compare(object.ResourceName, s.Name) == 0 { + + l.Debug.Printf("[COLLECTION] Event send cleaned from the processing list..\n") + + remotelist = append(remotelist[:i], remotelist[i+1:]...) + + break + + } + + } + + } + + ok = true + + return + +} + +// getStatus job is to normalize the event state returned by the collectors. +// Parameters: +// - state: string returned by the system. +// Returns: +// - status: normalized state to be returned. +func getStatus(state string) (status string) { + + switch strings.ToUpper(state) { + + case "ACTIVE": + + status = "active" + + case "ATTACHING": + + status = "active" + + case "AVAILABLE": + + status = "active" + + case "BUILD": + + status = "inactive" + + case "CREATING": + + status = "active" + + case "DELETED": + + status = "terminated" + + case "DELETING": + + status = "terminated" + + case "DETACHING": + + status = "active" + + case "DOWN": + + status = "inactive" + + case "ERROR": + + status = "error" + + case "ERROR_DELETING": + + status = "error" + + case "EXTENDING": + + status = "inactive" + + case "HARD_DELETED": + + status = "terminated" + + case "IN-USE": + + status = "active" + + case "MAINTENANCE": + + status = "active" + + case "PAUSED": + + status = "inactive" + + case "RESCUED": + + status = "active" + + case "RESIZE": + + status = "active" + + case "RESIZED": + + status = "active" + + case "RESERVED": + + status = "active" + + case "RETYPING": + + status = "inactive" + + case "SHELVED_OFFLOADED": + + status = "terminated" + + case "SHUTOFF": + + status = "inactive" + + case "SOFT_DELETED": + + status = "terminated" + + case "STOPPED": + + status = "inactive" + + case "SUSPENDED": + + status = "inactive" + + case "TERMINATED": + + status = "terminated" + + case "VERIFY_RESIZE": + + status = "active" + + } + + l.Trace.Printf("[REPORT] State received from the system [ %v ] normalized to [ %v ]", state, status) + + return status + +} diff --git a/cyclops-collectors/servers-collector/collector/config.go b/cyclops-collectors/servers-collector/collector/config.go new file mode 100644 index 0000000..b31a94d --- /dev/null +++ b/cyclops-collectors/servers-collector/collector/config.go @@ -0,0 +1,246 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool + Key string + Place string + Token string +} + +type configuration struct { + APIKey apiKey + General generalConfig + Heappe heappeConfig + Kafka kafkaConfig + Keycloak keycloakConfig + Lieutenant lieutenantConfig + OpenStack openStackConfig + Prometheus prometheusConfig + RGW rgwConfig + NameFilters []string + ProjectFilters []string + Services map[string]string +} + +type generalConfig struct { + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ObjectsPeriodicity int + Periodicity int + PrometheusPeriodicity int +} + +type heappeConfig struct { + Username string + Password string + GroupResourceUsageReportURI string + AuthenticateUserPasswordURI string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TLSEnabled bool + TopicUDR string + TopicEEngine string +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type lieutenantConfig struct { + Host string + Token string +} + +type openStackConfig struct { + Domain string + Keystone string + Password string + Project string + Region string + User string +} + +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +type rgwConfig struct { + AccessKeyID string + AdminPath string + Region string + SecretAccessKey string + ServerURL string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.Heappe.Username = masked(c.Heappe.Username, 4) + cfgCopy.Heappe.Password = masked(c.Heappe.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + cfgCopy.Lieutenant.Token = masked(c.Lieutenant.Token, 4) + cfgCopy.OpenStack.Password = masked(c.OpenStack.Password, 4) + cfgCopy.RGW.AccessKeyID = masked(c.RGW.AccessKeyID, 4) + cfgCopy.RGW.SecretAccessKey = masked(c.RGW.SecretAccessKey, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + General: generalConfig{ + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ObjectsPeriodicity: viper.GetInt("general.objectsperiodicity"), + Periodicity: viper.GetInt("general.periodicity"), + PrometheusPeriodicity: viper.GetInt("general.prometheusperiodicity"), + }, + + Heappe: heappeConfig{ + Username: viper.GetString("heappe.username"), + Password: viper.GetString("heappe.password"), + GroupResourceUsageReportURI: viper.GetString("heappe.groupResourceUsageReportUri"), + AuthenticateUserPasswordURI: viper.GetString("heappe.authenticateUserPasswordUri"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + TopicUDR: viper.GetString("kafka.topicudr"), + TopicEEngine: viper.GetString("kafka.topiceengine"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + Lieutenant: lieutenantConfig{ + Host: viper.GetString("lieutenant.host"), + Token: viper.GetString("lieutenant.token"), + }, + + OpenStack: openStackConfig{ + Domain: viper.GetString("openstack.domain"), + Keystone: viper.GetString("openstack.keystone"), + Password: viper.GetString("openstack.password"), + Project: viper.GetString("openstack.project"), + Region: viper.GetString("openstack.region"), + User: viper.GetString("openstack.user"), + }, + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + + RGW: rgwConfig{ + AccessKeyID: viper.GetString("rgw.accesskey"), + AdminPath: viper.GetString("rgw.adminpath"), + Region: viper.GetString("rgw.region"), + SecretAccessKey: viper.GetString("rgw.secretaccesskey"), + ServerURL: viper.GetString("rgw.serverurl"), + }, + + NameFilters: viper.GetStringSlice("events.namefilters"), + ProjectFilters: viper.GetStringSlice("events.projectfilters"), + Services: viper.GetStringMapString("services"), + } + + return + +} diff --git a/cyclops-collectors/servers-collector/collector/kafka.go b/cyclops-collectors/servers-collector/collector/kafka.go new file mode 100644 index 0000000..b265a2a --- /dev/null +++ b/cyclops-collectors/servers-collector/collector/kafka.go @@ -0,0 +1,137 @@ +package main + +import ( + "context" + "crypto/tls" + "encoding/json" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/segmentio/kafka-go" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaHandlerConf struct { + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + channel chan interface{} +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.out != nil { + + for _, p := range kH.out { + + go kafkaSender(p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Go Channel Problems"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "Kafka Stream Problems"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "OK", "reason": "Object sent"}).Inc() + + } + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + metricReporting.With(prometheus.Labels{"topic": t, "state": "FAIL", "reason": "JSON Marshalling"}).Inc() + + } + + return + + }() + + } + +} diff --git a/cyclops-collectors/servers-collector/collector/main.go b/cyclops-collectors/servers-collector/collector/main.go new file mode 100644 index 0000000..c12cdac --- /dev/null +++ b/cyclops-collectors/servers-collector/collector/main.go @@ -0,0 +1,192 @@ +package main + +import ( + "flag" + "fmt" + "net/url" + "os" + "reflect" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/spf13/viper" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + eeClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + version string + cfg configuration + pipeU chan interface{} + pipeE chan interface{} + reportClient *eeClient.EventEngineManagementAPI + zombiesClient *cusClient.CustomerDatabaseManagement +) + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Returns: +// - ch: a interface{} channel to be able to send things through the kafka topic +// generated. +func kafkaStart() (chUDR, chEvents chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + chUDR = make(chan interface{}, 1000) + chEvents = make(chan interface{}, 1000) + + handler := kafkaHandlerConf{ + out: []kafkaPackage{ + { + topic: cfg.Kafka.TopicUDR, + channel: chUDR, + }, + { + topic: cfg.Kafka.TopicEEngine, + channel: chEvents, + }, + }, + } + + kafkaHandler(handler) + + return + +} + +// report handles the process of sending the event or usage to the respective +// service. +// Parameters: +// - object: an interface{} reference with the event/usage to be sent. +func report(object interface{}) { + + l.Trace.Printf("[REPORT] The reporting process has been started.\n") + + if reflect.TypeOf(object) == reflect.TypeOf(udrModels.Usage{}) { + + l.Trace.Printf("[REPORT] UDR Object detected. Sending through kafka.\n") + + pipeU <- object + + return + + } + + if reflect.TypeOf(object) == reflect.TypeOf(eeModels.Event{}) { + + l.Trace.Printf("[REPORT] Event Object detected. Sending through kafka.\n") + + pipeE <- object + + return + + } + + fail := "the provided object doesn't belong to UDR or EE models" + + l.Warning.Printf("[REPORT] Something went wrong while processing the object, check with the administrator. Error: %v.\n", fail) + + return + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: Collector-TYPE -conf=/path/to/configuration/file\n") + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %s\nCorrect usage: Collector-TYPE -conf=/path/to/configuration/file\n", err) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs Collector TYPE version %v initialized\n", version) + + dumpConfig(cfg) + + // Let's start the HTTP Server and Gauges for Prometheus + prometheusStart() + +} + +func main() { + + // If needed here is the initialization for the kafka sender: + pipeU, pipeE = kafkaStart() + + // Here we start the client instantiation to send reports to the EventsEngine. + eeConfig := eeClient.Config{ + URL: &url.URL{ + Host: cfg.Services["eventsengine"], + Path: eeClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + reportClient = eeClient.New(eeConfig) + + // Here we start the client instantiation to get the canceled customers to check for zombies. + cusConfig := cusClient.Config{ + URL: &url.URL{ + Host: cfg.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + zombiesClient = cusClient.New(cusConfig) + + // Start of the caches + FlavorCache = make(map[string]FlavorIDCacheData) + ImageCache = make(map[string]ImageIDCacheData) + + // Let's lunch the first collection process.. + go collect() + + // cfg.General.Periodicity should be changed to cfg.General.ObjectPeriodicity + // in the case you need the long (8h) periodicity. + for range time.NewTicker(time.Duration(cfg.General.Periodicity) * time.Minute).C { + + go collect() + + } + +} diff --git a/cyclops-collectors/servers-collector/collector/metrics.go b/cyclops-collectors/servers-collector/collector/metrics.go new file mode 100644 index 0000000..4f7d9ec --- /dev/null +++ b/cyclops-collectors/servers-collector/collector/metrics.go @@ -0,0 +1,95 @@ +package main + +import ( + "log" + "net/http" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricReporting *prometheus.GaugeVec + metricCollection *prometheus.GaugeVec + metricTime *prometheus.GaugeVec + metricCount *prometheus.GaugeVec +) + +func prometheusStart() { + + reg := prometheus.NewPedanticRegistry() + + metricReporting = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "kafka_send_state", + Help: "Reporting information and Kafka topics usage", + }, + []string{ + "reason", + "state", + "topic", + }, + ) + + metricCollection = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "Collection", + Help: "Collection information and usages data", + }, + []string{ + "account", + "event", + "reason", + "state", + "type", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: "collection_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + metricCount = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: collector + "_Collector", + Name: objects + "_count", + Help: "Different VM Counts", + }, + []string{ + "type", + }, + ) + + reg.MustRegister(metricReporting, metricCollection, metricTime, metricCount) + //prometheus.MustRegister(metricReporting, metricCollection) + + l.Trace.Printf("[Prometheus] Starting to serve the metrics.\n") + + go func() { + + if cfg.Prometheus.MetricsExport { + + //http.Handle(cfg.Prometheus.MetricsRoute, promhttp.Handler()) + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) + + go log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + } + + }() + +} diff --git a/cyclops-collectors/servers-collector/go.mod b/cyclops-collectors/servers-collector/go.mod new file mode 100644 index 0000000..fd37614 --- /dev/null +++ b/cyclops-collectors/servers-collector/go.mod @@ -0,0 +1,28 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/cyclops-collectors/servers-collector + +go 1.13 + +require ( + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/go-openapi/analysis v0.21.1 // indirect + github.com/go-openapi/runtime v0.21.0 + github.com/go-stack/stack v1.8.1 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/gophercloud/gophercloud v0.23.0 + github.com/klauspost/cpuid/v2 v2.0.9 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/pierrec/lz4 v2.6.1+incompatible // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/segmentio/kafka-go v0.4.23 + github.com/spf13/viper v1.9.0 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + go.mongodb.org/mongo-driver v1.7.4 // indirect + golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1 // indirect +) diff --git a/cyclops-collectors/servers-collector/run/cert.crt b/cyclops-collectors/servers-collector/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/servers-collector/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/cyclops-collectors/servers-collector/run/config.toml b/cyclops-collectors/servers-collector/run/config.toml new file mode 100644 index 0000000..17d47d4 --- /dev/null +++ b/cyclops-collectors/servers-collector/run/config.toml @@ -0,0 +1,93 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# collector! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[EVENTS] +Filters = [ "filter1", "filter2", "filter3" ] + +[GENERAL] +LogFile = "" +LogToConsole = true +# loglevel values can be one of the following: TRACE, DEBUG, INFO, WARNING, ERROR +LogLevel = "TRACE" +ObjectsPeriodicity = 480 +Periodicity = 15 +PrometheusPeriodicity = 60 + +[HEAPPE] +Username = "" +Password = "" +GroupResourceUsageReportUri = "" +AuthenticateUserPasswordUri = "" + +[KAFKA] +Brokers = [ "broker-1-IP:broker-1-PORT", "broker-2-IP:broker-2-PORT", "broker-3-IP:broker-3-PORT" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMax = 10e6 +SizeMin = 10e3 +TLSEnabled = false +TopicEEngine = "Events" +TopicUDR = "UDR" + +[KEYCLOAK] +ClientID = "SERVICE" +ClientSecret = "00000000-0000-0000-0000-00000000" +Enabled = true +Host = "0.0.0.0" +Port = 8080 +Realm = "Development" +RedirectURL = "" +UseHttp = true + +[LIEUTENANT] +Host = "lieutenant:4010" +Token = "" + +[OPENSTACK] +Domain = "" +Keystone = "" +Password = "" +Project = "" +Region = "" +User = "" + +[PROMETHEUS] +Host = "prometheus:9000" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + +[RGW] +AccessKey = "" +AdminPath = "" +Region = "" +SecretAccessKey = "" +ServerURL = "" + +[SERVICES] +CustomerDB = "localhost:8400" +EventsEngine = "localhost:8500" diff --git a/cyclops-collectors/servers-collector/run/docker-compose.yml b/cyclops-collectors/servers-collector/run/docker-compose.yml new file mode 100644 index 0000000..a90ef54 --- /dev/null +++ b/cyclops-collectors/servers-collector/run/docker-compose.yml @@ -0,0 +1,17 @@ +version: '3' + +services: + + collectors: + environment: + WAIT_AFTER_HOSTS: 30 + image: servers-collector:latest + networks: + - collectorsnet + restart: always + volumes: + - ${PWD}/config.toml:/config.toml + +networks: + collectorsnet: + driver: bridge diff --git a/cyclops-collectors/servers-collector/run/key.key b/cyclops-collectors/servers-collector/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/cyclops-collectors/servers-collector/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/extensions/lexis/README.md b/extensions/lexis/README.md new file mode 100644 index 0000000..5a6889c --- /dev/null +++ b/extensions/lexis/README.md @@ -0,0 +1,27 @@ +# LEXIS EXTENSIONs SERVICE + +Cyclops Engine's Extension Service for LEXIS implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + + diff --git a/extensions/lexis/client/l_e_x_i_s_extension_management_api_client.go b/extensions/lexis/client/l_e_x_i_s_extension_management_api_client.go new file mode 100644 index 0000000..962a676 --- /dev/null +++ b/extensions/lexis/client/l_e_x_i_s_extension_management_api_client.go @@ -0,0 +1,75 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/client/sync_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/client/trigger_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v0.1" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new l e x i s extension management API HTTP client. +func New(c Config) *LEXISExtensionManagementAPI { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(LEXISExtensionManagementAPI) + cli.Transport = transport + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.SyncManagement = sync_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// LEXISExtensionManagementAPI is a client for l e x i s extension management API +type LEXISExtensionManagementAPI struct { + StatusManagement *status_management.Client + SyncManagement *sync_management.Client + TriggerManagement *trigger_management.Client + Transport runtime.ClientTransport +} diff --git a/extensions/lexis/client/status_management/get_status_parameters.go b/extensions/lexis/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..bc38256 --- /dev/null +++ b/extensions/lexis/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the endpoint to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/client/status_management/get_status_responses.go b/extensions/lexis/client/status_management/get_status_responses.go new file mode 100644 index 0000000..9c4c5a7 --- /dev/null +++ b/extensions/lexis/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/extensions/lexis/client/status_management/show_status_parameters.go b/extensions/lexis/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/extensions/lexis/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/client/status_management/show_status_responses.go b/extensions/lexis/client/status_management/show_status_responses.go new file mode 100644 index 0000000..dfb0347 --- /dev/null +++ b/extensions/lexis/client/status_management/show_status_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/extensions/lexis/client/status_management/status_management_client.go b/extensions/lexis/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/extensions/lexis/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/extensions/lexis/client/sync_management/sync_flavors_parameters.go b/extensions/lexis/client/sync_management/sync_flavors_parameters.go new file mode 100644 index 0000000..f886095 --- /dev/null +++ b/extensions/lexis/client/sync_management/sync_flavors_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewSyncFlavorsParams creates a new SyncFlavorsParams object +// with the default values initialized. +func NewSyncFlavorsParams() *SyncFlavorsParams { + + return &SyncFlavorsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewSyncFlavorsParamsWithTimeout creates a new SyncFlavorsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewSyncFlavorsParamsWithTimeout(timeout time.Duration) *SyncFlavorsParams { + + return &SyncFlavorsParams{ + + timeout: timeout, + } +} + +// NewSyncFlavorsParamsWithContext creates a new SyncFlavorsParams object +// with the default values initialized, and the ability to set a context for a request +func NewSyncFlavorsParamsWithContext(ctx context.Context) *SyncFlavorsParams { + + return &SyncFlavorsParams{ + + Context: ctx, + } +} + +// NewSyncFlavorsParamsWithHTTPClient creates a new SyncFlavorsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewSyncFlavorsParamsWithHTTPClient(client *http.Client) *SyncFlavorsParams { + + return &SyncFlavorsParams{ + HTTPClient: client, + } +} + +/*SyncFlavorsParams contains all the parameters to send to the API endpoint +for the sync flavors operation typically these are written to a http.Request +*/ +type SyncFlavorsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the sync flavors params +func (o *SyncFlavorsParams) WithTimeout(timeout time.Duration) *SyncFlavorsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the sync flavors params +func (o *SyncFlavorsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the sync flavors params +func (o *SyncFlavorsParams) WithContext(ctx context.Context) *SyncFlavorsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the sync flavors params +func (o *SyncFlavorsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the sync flavors params +func (o *SyncFlavorsParams) WithHTTPClient(client *http.Client) *SyncFlavorsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the sync flavors params +func (o *SyncFlavorsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *SyncFlavorsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/client/sync_management/sync_flavors_responses.go b/extensions/lexis/client/sync_management/sync_flavors_responses.go new file mode 100644 index 0000000..436a83a --- /dev/null +++ b/extensions/lexis/client/sync_management/sync_flavors_responses.go @@ -0,0 +1,123 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// SyncFlavorsReader is a Reader for the SyncFlavors structure. +type SyncFlavorsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *SyncFlavorsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewSyncFlavorsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 202: + result := NewSyncFlavorsAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewSyncFlavorsInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewSyncFlavorsOK creates a SyncFlavorsOK with default headers values +func NewSyncFlavorsOK() *SyncFlavorsOK { + return &SyncFlavorsOK{} +} + +/*SyncFlavorsOK handles this case with default header values. + +The load of data was completely successfully +*/ +type SyncFlavorsOK struct { +} + +func (o *SyncFlavorsOK) Error() string { + return fmt.Sprintf("[GET /sync/flavors][%d] syncFlavorsOK ", 200) +} + +func (o *SyncFlavorsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewSyncFlavorsAccepted creates a SyncFlavorsAccepted with default headers values +func NewSyncFlavorsAccepted() *SyncFlavorsAccepted { + return &SyncFlavorsAccepted{} +} + +/*SyncFlavorsAccepted handles this case with default header values. + +Operation done but there might have been some fails when adding part of the data +*/ +type SyncFlavorsAccepted struct { +} + +func (o *SyncFlavorsAccepted) Error() string { + return fmt.Sprintf("[GET /sync/flavors][%d] syncFlavorsAccepted ", 202) +} + +func (o *SyncFlavorsAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewSyncFlavorsInternalServerError creates a SyncFlavorsInternalServerError with default headers values +func NewSyncFlavorsInternalServerError() *SyncFlavorsInternalServerError { + return &SyncFlavorsInternalServerError{} +} + +/*SyncFlavorsInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type SyncFlavorsInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *SyncFlavorsInternalServerError) Error() string { + return fmt.Sprintf("[GET /sync/flavors][%d] syncFlavorsInternalServerError %+v", 500, o.Payload) +} + +func (o *SyncFlavorsInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *SyncFlavorsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/extensions/lexis/client/sync_management/sync_hierarchy_parameters.go b/extensions/lexis/client/sync_management/sync_hierarchy_parameters.go new file mode 100644 index 0000000..5eac205 --- /dev/null +++ b/extensions/lexis/client/sync_management/sync_hierarchy_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewSyncHierarchyParams creates a new SyncHierarchyParams object +// with the default values initialized. +func NewSyncHierarchyParams() *SyncHierarchyParams { + + return &SyncHierarchyParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewSyncHierarchyParamsWithTimeout creates a new SyncHierarchyParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewSyncHierarchyParamsWithTimeout(timeout time.Duration) *SyncHierarchyParams { + + return &SyncHierarchyParams{ + + timeout: timeout, + } +} + +// NewSyncHierarchyParamsWithContext creates a new SyncHierarchyParams object +// with the default values initialized, and the ability to set a context for a request +func NewSyncHierarchyParamsWithContext(ctx context.Context) *SyncHierarchyParams { + + return &SyncHierarchyParams{ + + Context: ctx, + } +} + +// NewSyncHierarchyParamsWithHTTPClient creates a new SyncHierarchyParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewSyncHierarchyParamsWithHTTPClient(client *http.Client) *SyncHierarchyParams { + + return &SyncHierarchyParams{ + HTTPClient: client, + } +} + +/*SyncHierarchyParams contains all the parameters to send to the API endpoint +for the sync hierarchy operation typically these are written to a http.Request +*/ +type SyncHierarchyParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the sync hierarchy params +func (o *SyncHierarchyParams) WithTimeout(timeout time.Duration) *SyncHierarchyParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the sync hierarchy params +func (o *SyncHierarchyParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the sync hierarchy params +func (o *SyncHierarchyParams) WithContext(ctx context.Context) *SyncHierarchyParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the sync hierarchy params +func (o *SyncHierarchyParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the sync hierarchy params +func (o *SyncHierarchyParams) WithHTTPClient(client *http.Client) *SyncHierarchyParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the sync hierarchy params +func (o *SyncHierarchyParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *SyncHierarchyParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/client/sync_management/sync_hierarchy_responses.go b/extensions/lexis/client/sync_management/sync_hierarchy_responses.go new file mode 100644 index 0000000..342924f --- /dev/null +++ b/extensions/lexis/client/sync_management/sync_hierarchy_responses.go @@ -0,0 +1,123 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// SyncHierarchyReader is a Reader for the SyncHierarchy structure. +type SyncHierarchyReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *SyncHierarchyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewSyncHierarchyOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 202: + result := NewSyncHierarchyAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewSyncHierarchyInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewSyncHierarchyOK creates a SyncHierarchyOK with default headers values +func NewSyncHierarchyOK() *SyncHierarchyOK { + return &SyncHierarchyOK{} +} + +/*SyncHierarchyOK handles this case with default header values. + +The load of data was completely successfully +*/ +type SyncHierarchyOK struct { +} + +func (o *SyncHierarchyOK) Error() string { + return fmt.Sprintf("[GET /sync/hierarchy][%d] syncHierarchyOK ", 200) +} + +func (o *SyncHierarchyOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewSyncHierarchyAccepted creates a SyncHierarchyAccepted with default headers values +func NewSyncHierarchyAccepted() *SyncHierarchyAccepted { + return &SyncHierarchyAccepted{} +} + +/*SyncHierarchyAccepted handles this case with default header values. + +Operation done but there might have been some fails when adding part of the data +*/ +type SyncHierarchyAccepted struct { +} + +func (o *SyncHierarchyAccepted) Error() string { + return fmt.Sprintf("[GET /sync/hierarchy][%d] syncHierarchyAccepted ", 202) +} + +func (o *SyncHierarchyAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewSyncHierarchyInternalServerError creates a SyncHierarchyInternalServerError with default headers values +func NewSyncHierarchyInternalServerError() *SyncHierarchyInternalServerError { + return &SyncHierarchyInternalServerError{} +} + +/*SyncHierarchyInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type SyncHierarchyInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *SyncHierarchyInternalServerError) Error() string { + return fmt.Sprintf("[GET /sync/hierarchy][%d] syncHierarchyInternalServerError %+v", 500, o.Payload) +} + +func (o *SyncHierarchyInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *SyncHierarchyInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/extensions/lexis/client/sync_management/sync_management_client.go b/extensions/lexis/client/sync_management/sync_management_client.go new file mode 100644 index 0000000..93ddbd1 --- /dev/null +++ b/extensions/lexis/client/sync_management/sync_management_client.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the sync management client +type API interface { + /* + SyncFlavors syncs the open stack s flavors data in the system*/ + SyncFlavors(ctx context.Context, params *SyncFlavorsParams) (*SyncFlavorsOK, *SyncFlavorsAccepted, error) + /* + SyncHierarchy syncs all the organizations projects resources hierarchy from l e x i s*/ + SyncHierarchy(ctx context.Context, params *SyncHierarchyParams) (*SyncHierarchyOK, *SyncHierarchyAccepted, error) +} + +// New creates a new sync management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for sync management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +SyncFlavors syncs the open stack s flavors data in the system +*/ +func (a *Client) SyncFlavors(ctx context.Context, params *SyncFlavorsParams) (*SyncFlavorsOK, *SyncFlavorsAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "syncFlavors", + Method: "GET", + PathPattern: "/sync/flavors", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &SyncFlavorsReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, nil, err + } + switch value := result.(type) { + case *SyncFlavorsOK: + return value, nil, nil + case *SyncFlavorsAccepted: + return nil, value, nil + } + return nil, nil, nil + +} + +/* +SyncHierarchy syncs all the organizations projects resources hierarchy from l e x i s +*/ +func (a *Client) SyncHierarchy(ctx context.Context, params *SyncHierarchyParams) (*SyncHierarchyOK, *SyncHierarchyAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "syncHierarchy", + Method: "GET", + PathPattern: "/sync/hierarchy", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &SyncHierarchyReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, nil, err + } + switch value := result.(type) { + case *SyncHierarchyOK: + return value, nil, nil + case *SyncHierarchyAccepted: + return nil, value, nil + } + return nil, nil, nil + +} diff --git a/extensions/lexis/client/trigger_management/trigger_management_client.go b/extensions/lexis/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..3530cc8 --- /dev/null +++ b/extensions/lexis/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + UDRRedo redos of u d rs from the specific dates and with the specifc interval*/ + UDRRedo(ctx context.Context, params *UDRRedoParams) (*UDRRedoOK, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +UDRRedo redos of u d rs from the specific dates and with the specifc interval +*/ +func (a *Client) UDRRedo(ctx context.Context, params *UDRRedoParams) (*UDRRedoOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "UDRRedo", + Method: "GET", + PathPattern: "/trigger/udrsredo", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UDRRedoReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UDRRedoOK), nil + +} diff --git a/extensions/lexis/client/trigger_management/u_d_r_redo_parameters.go b/extensions/lexis/client/trigger_management/u_d_r_redo_parameters.go new file mode 100644 index 0000000..8c20fbd --- /dev/null +++ b/extensions/lexis/client/trigger_management/u_d_r_redo_parameters.go @@ -0,0 +1,210 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewUDRRedoParams creates a new UDRRedoParams object +// with the default values initialized. +func NewUDRRedoParams() *UDRRedoParams { + var () + return &UDRRedoParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUDRRedoParamsWithTimeout creates a new UDRRedoParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUDRRedoParamsWithTimeout(timeout time.Duration) *UDRRedoParams { + var () + return &UDRRedoParams{ + + timeout: timeout, + } +} + +// NewUDRRedoParamsWithContext creates a new UDRRedoParams object +// with the default values initialized, and the ability to set a context for a request +func NewUDRRedoParamsWithContext(ctx context.Context) *UDRRedoParams { + var () + return &UDRRedoParams{ + + Context: ctx, + } +} + +// NewUDRRedoParamsWithHTTPClient creates a new UDRRedoParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUDRRedoParamsWithHTTPClient(client *http.Client) *UDRRedoParams { + var () + return &UDRRedoParams{ + HTTPClient: client, + } +} + +/*UDRRedoParams contains all the parameters to send to the API endpoint +for the u d r redo operation typically these are written to a http.Request +*/ +type UDRRedoParams struct { + + /*From + Datetime from which to regenerate the udrs + + */ + From *strfmt.DateTime + /*Interval + Interval to do increments + + */ + Interval *string + /*To + Datetime until which to regenerate the udrs + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the u d r redo params +func (o *UDRRedoParams) WithTimeout(timeout time.Duration) *UDRRedoParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the u d r redo params +func (o *UDRRedoParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the u d r redo params +func (o *UDRRedoParams) WithContext(ctx context.Context) *UDRRedoParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the u d r redo params +func (o *UDRRedoParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the u d r redo params +func (o *UDRRedoParams) WithHTTPClient(client *http.Client) *UDRRedoParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the u d r redo params +func (o *UDRRedoParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the u d r redo params +func (o *UDRRedoParams) WithFrom(from *strfmt.DateTime) *UDRRedoParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the u d r redo params +func (o *UDRRedoParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithInterval adds the interval to the u d r redo params +func (o *UDRRedoParams) WithInterval(interval *string) *UDRRedoParams { + o.SetInterval(interval) + return o +} + +// SetInterval adds the interval to the u d r redo params +func (o *UDRRedoParams) SetInterval(interval *string) { + o.Interval = interval +} + +// WithTo adds the to to the u d r redo params +func (o *UDRRedoParams) WithTo(to *strfmt.DateTime) *UDRRedoParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the u d r redo params +func (o *UDRRedoParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *UDRRedoParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + if o.Interval != nil { + + // query param interval + var qrInterval string + if o.Interval != nil { + qrInterval = *o.Interval + } + qInterval := qrInterval + if qInterval != "" { + if err := r.SetQueryParam("interval", qInterval); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/client/trigger_management/u_d_r_redo_responses.go b/extensions/lexis/client/trigger_management/u_d_r_redo_responses.go new file mode 100644 index 0000000..5dd88d5 --- /dev/null +++ b/extensions/lexis/client/trigger_management/u_d_r_redo_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// UDRRedoReader is a Reader for the UDRRedo structure. +type UDRRedoReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UDRRedoReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUDRRedoOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewUDRRedoInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewUDRRedoOK creates a UDRRedoOK with default headers values +func NewUDRRedoOK() *UDRRedoOK { + return &UDRRedoOK{} +} + +/*UDRRedoOK handles this case with default header values. + +Generation task executed successfully. +*/ +type UDRRedoOK struct { + Payload *models.ItemCreatedResponse +} + +func (o *UDRRedoOK) Error() string { + return fmt.Sprintf("[GET /trigger/udrsredo][%d] uDRRedoOK %+v", 200, o.Payload) +} + +func (o *UDRRedoOK) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *UDRRedoOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUDRRedoInternalServerError creates a UDRRedoInternalServerError with default headers values +func NewUDRRedoInternalServerError() *UDRRedoInternalServerError { + return &UDRRedoInternalServerError{} +} + +/*UDRRedoInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type UDRRedoInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UDRRedoInternalServerError) Error() string { + return fmt.Sprintf("[GET /trigger/udrsredo][%d] uDRRedoInternalServerError %+v", 500, o.Payload) +} + +func (o *UDRRedoInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UDRRedoInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/extensions/lexis/go.mod b/extensions/lexis/go.mod new file mode 100644 index 0000000..b8af168 --- /dev/null +++ b/extensions/lexis/go.mod @@ -0,0 +1,45 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis + +go 1.16 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/go-stack/stack v1.8.1 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/gophercloud/gophercloud v0.24.0 + github.com/jackc/pgx/v4 v4.14.1 // indirect + github.com/jinzhu/now v1.1.4 // indirect + github.com/klauspost/cpuid/v2 v2.0.9 // indirect + github.com/lib/pq v1.10.4 + github.com/pierrec/lz4 v2.6.1+incompatible // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/rs/cors v1.8.0 + github.com/segmentio/asm v1.1.3 // indirect + github.com/segmentio/encoding v0.3.2 + github.com/segmentio/kafka-go v0.4.25 + github.com/segmentio/ksuid v1.0.4 // indirect + github.com/spf13/viper v1.10.1 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + go.mongodb.org/mongo-driver v1.8.1 // indirect + golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect + golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect + golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/extensions/lexis/models/error_response.go b/extensions/lexis/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/extensions/lexis/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/extensions/lexis/models/h_p_c_resource.go b/extensions/lexis/models/h_p_c_resource.go new file mode 100644 index 0000000..2f14328 --- /dev/null +++ b/extensions/lexis/models/h_p_c_resource.go @@ -0,0 +1,253 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// HPCResource h p c resource +// +// swagger:model HPCResource +type HPCResource struct { + + // approval status + // Enum: [ACCEPTED REJECTED PENDING] + ApprovalStatus string `json:"ApprovalStatus,omitempty" gorm:"column:approvalstatus"` + + // associated h p c project + AssociatedHPCProject string `json:"AssociatedHPCProject,omitempty" gorm:"column:associatedhpcproject"` + + // associated l e x i s project + // Format: uuid + AssociatedLEXISProject strfmt.UUID `json:"AssociatedLEXISProject,omitempty" gorm:"column:associatedlexisproject;type:uuid"` + + // cloud network name + CloudNetworkName string `json:"CloudNetworkName,omitempty" gorm:"column:cloudnetworkname"` + + // h e app e endpoint + HEAppEEndpoint string `json:"HEAppEEndpoint,omitempty" gorm:"column:heappeendpoint"` + + // h p c provider + // Enum: [IT4I LRZ ICHEC] + HPCProvider string `json:"HPCProvider,omitempty" gorm:"column:hpcprovider"` + + // h p c resource ID + HPCResourceID string `json:"HPCResourceID,omitempty" gorm:"column:hpcresourceid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // open stack endpoint + OpenStackEndpoint string `json:"OpenStackEndpoint,omitempty" gorm:"column:openstackendpoint"` + + // open stack project ID + OpenStackProjectID string `json:"OpenStackProjectID,omitempty" gorm:"column:openstackprojectid"` + + // project network name + ProjectNetworkName string `json:"ProjectNetworkName,omitempty" gorm:"column:projectnetworkname"` + + // resource type + // Enum: [CLOUD HPC] + ResourceType string `json:"ResourceType,omitempty" gorm:"column:resourcetype"` + + // terms consent + TermsConsent bool `json:"TermsConsent,omitempty" gorm:"column:termsconsent;type:bool"` +} + +// Validate validates this h p c resource +func (m *HPCResource) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateApprovalStatus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateAssociatedLEXISProject(formats); err != nil { + res = append(res, err) + } + + if err := m.validateHPCProvider(formats); err != nil { + res = append(res, err) + } + + if err := m.validateResourceType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var hPCResourceTypeApprovalStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ACCEPTED","REJECTED","PENDING"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + hPCResourceTypeApprovalStatusPropEnum = append(hPCResourceTypeApprovalStatusPropEnum, v) + } +} + +const ( + + // HPCResourceApprovalStatusACCEPTED captures enum value "ACCEPTED" + HPCResourceApprovalStatusACCEPTED string = "ACCEPTED" + + // HPCResourceApprovalStatusREJECTED captures enum value "REJECTED" + HPCResourceApprovalStatusREJECTED string = "REJECTED" + + // HPCResourceApprovalStatusPENDING captures enum value "PENDING" + HPCResourceApprovalStatusPENDING string = "PENDING" +) + +// prop value enum +func (m *HPCResource) validateApprovalStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, hPCResourceTypeApprovalStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *HPCResource) validateApprovalStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.ApprovalStatus) { // not required + return nil + } + + // value enum + if err := m.validateApprovalStatusEnum("ApprovalStatus", "body", m.ApprovalStatus); err != nil { + return err + } + + return nil +} + +func (m *HPCResource) validateAssociatedLEXISProject(formats strfmt.Registry) error { + + if swag.IsZero(m.AssociatedLEXISProject) { // not required + return nil + } + + if err := validate.FormatOf("AssociatedLEXISProject", "body", "uuid", m.AssociatedLEXISProject.String(), formats); err != nil { + return err + } + + return nil +} + +var hPCResourceTypeHPCProviderPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["IT4I","LRZ","ICHEC"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + hPCResourceTypeHPCProviderPropEnum = append(hPCResourceTypeHPCProviderPropEnum, v) + } +} + +const ( + + // HPCResourceHPCProviderIT4I captures enum value "IT4I" + HPCResourceHPCProviderIT4I string = "IT4I" + + // HPCResourceHPCProviderLRZ captures enum value "LRZ" + HPCResourceHPCProviderLRZ string = "LRZ" + + // HPCResourceHPCProviderICHEC captures enum value "ICHEC" + HPCResourceHPCProviderICHEC string = "ICHEC" +) + +// prop value enum +func (m *HPCResource) validateHPCProviderEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, hPCResourceTypeHPCProviderPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *HPCResource) validateHPCProvider(formats strfmt.Registry) error { + + if swag.IsZero(m.HPCProvider) { // not required + return nil + } + + // value enum + if err := m.validateHPCProviderEnum("HPCProvider", "body", m.HPCProvider); err != nil { + return err + } + + return nil +} + +var hPCResourceTypeResourceTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CLOUD","HPC"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + hPCResourceTypeResourceTypePropEnum = append(hPCResourceTypeResourceTypePropEnum, v) + } +} + +const ( + + // HPCResourceResourceTypeCLOUD captures enum value "CLOUD" + HPCResourceResourceTypeCLOUD string = "CLOUD" + + // HPCResourceResourceTypeHPC captures enum value "HPC" + HPCResourceResourceTypeHPC string = "HPC" +) + +// prop value enum +func (m *HPCResource) validateResourceTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, hPCResourceTypeResourceTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *HPCResource) validateResourceType(formats strfmt.Registry) error { + + if swag.IsZero(m.ResourceType) { // not required + return nil + } + + // value enum + if err := m.validateResourceTypeEnum("ResourceType", "body", m.ResourceType); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HPCResource) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HPCResource) UnmarshalBinary(b []byte) error { + var res HPCResource + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/extensions/lexis/models/item_created_response.go b/extensions/lexis/models/item_created_response.go new file mode 100644 index 0000000..c6c7e65 --- /dev/null +++ b/extensions/lexis/models/item_created_response.go @@ -0,0 +1,43 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ItemCreatedResponse item created response +// +// swagger:model ItemCreatedResponse +type ItemCreatedResponse struct { + + // message + Message string `json:"Message,omitempty"` +} + +// Validate validates this item created response +func (m *ItemCreatedResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ItemCreatedResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ItemCreatedResponse) UnmarshalBinary(b []byte) error { + var res ItemCreatedResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/extensions/lexis/models/organization.go b/extensions/lexis/models/organization.go new file mode 100644 index 0000000..0332220 --- /dev/null +++ b/extensions/lexis/models/organization.go @@ -0,0 +1,214 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Organization organization +// +// swagger:model Organization +type Organization struct { + + // created by + // Format: uuid + CreatedBy strfmt.UUID `json:"CreatedBy,omitempty" gorm:"column:createdby;type:uuid"` + + // creation date + // Format: date-time + CreationDate strfmt.DateTime `json:"CreationDate,omitempty" gorm:"column:registrationdatetime;type:timestamptz"` + + // formal name + FormalName string `json:"FormalName,omitempty" gorm:"column:formalname"` + + // ID + // Format: uuid + ID strfmt.UUID `json:"ID,omitempty" gorm:"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // organization email address + // Format: email + OrganizationEmailAddress strfmt.Email `json:"OrganizationEmailAddress,omitempty" gorm:"column:organizationemailaddress"` + + // organization status + // Enum: [PENDING_APPROVAL APPROVED DISABLED TERMINATED] + OrganizationStatus string `json:"OrganizationStatus,omitempty" gorm:"column:organizationstatus"` + + // primary telephone number + PrimaryTelephoneNumber string `json:"PrimaryTelephoneNumber,omitempty" gorm:"column:primarytelephonenumber"` + + // registered address1 + RegisteredAddress1 string `json:"RegisteredAddress1,omitempty" gorm:"column:registeredaddress1"` + + // registered address2 + RegisteredAddress2 string `json:"RegisteredAddress2,omitempty" gorm:"column:registeredaddress2"` + + // registered address3 + RegisteredAddress3 string `json:"RegisteredAddress3,omitempty" gorm:"column:registeredaddress3"` + + // registered country + RegisteredCountry string `json:"RegisteredCountry,omitempty" gorm:"column:registeredcountry"` + + // v a t registration number + VATRegistrationNumber string `json:"VATRegistrationNumber,omitempty" gorm:"column:vatregistrationnumber"` + + // website + Website string `json:"Website,omitempty"` +} + +// Validate validates this organization +func (m *Organization) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreatedBy(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCreationDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOrganizationEmailAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOrganizationStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Organization) validateCreatedBy(formats strfmt.Registry) error { + + if swag.IsZero(m.CreatedBy) { // not required + return nil + } + + if err := validate.FormatOf("CreatedBy", "body", "uuid", m.CreatedBy.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Organization) validateCreationDate(formats strfmt.Registry) error { + + if swag.IsZero(m.CreationDate) { // not required + return nil + } + + if err := validate.FormatOf("CreationDate", "body", "date-time", m.CreationDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Organization) validateID(formats strfmt.Registry) error { + + if swag.IsZero(m.ID) { // not required + return nil + } + + if err := validate.FormatOf("ID", "body", "uuid", m.ID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Organization) validateOrganizationEmailAddress(formats strfmt.Registry) error { + + if swag.IsZero(m.OrganizationEmailAddress) { // not required + return nil + } + + if err := validate.FormatOf("OrganizationEmailAddress", "body", "email", m.OrganizationEmailAddress.String(), formats); err != nil { + return err + } + + return nil +} + +var organizationTypeOrganizationStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["PENDING_APPROVAL","APPROVED","DISABLED","TERMINATED"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + organizationTypeOrganizationStatusPropEnum = append(organizationTypeOrganizationStatusPropEnum, v) + } +} + +const ( + + // OrganizationOrganizationStatusPENDINGAPPROVAL captures enum value "PENDING_APPROVAL" + OrganizationOrganizationStatusPENDINGAPPROVAL string = "PENDING_APPROVAL" + + // OrganizationOrganizationStatusAPPROVED captures enum value "APPROVED" + OrganizationOrganizationStatusAPPROVED string = "APPROVED" + + // OrganizationOrganizationStatusDISABLED captures enum value "DISABLED" + OrganizationOrganizationStatusDISABLED string = "DISABLED" + + // OrganizationOrganizationStatusTERMINATED captures enum value "TERMINATED" + OrganizationOrganizationStatusTERMINATED string = "TERMINATED" +) + +// prop value enum +func (m *Organization) validateOrganizationStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, organizationTypeOrganizationStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Organization) validateOrganizationStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.OrganizationStatus) { // not required + return nil + } + + // value enum + if err := m.validateOrganizationStatusEnum("OrganizationStatus", "body", m.OrganizationStatus); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Organization) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Organization) UnmarshalBinary(b []byte) error { + var res Organization + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/extensions/lexis/models/project.go b/extensions/lexis/models/project.go new file mode 100644 index 0000000..d219125 --- /dev/null +++ b/extensions/lexis/models/project.go @@ -0,0 +1,296 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "github.com/lib/pq" +) + +// Project project +// +// swagger:model Project +type Project struct { + + // allowed organizations + AllowedOrganizations pq.StringArray `json:"AllowedOrganizations,omitempty" gorm:"column:allowedorganizations;type:text[]"` + + // linked organization + // Format: uuid + LinkedOrganization strfmt.UUID `json:"LinkedOrganization,omitempty" gorm:"column:linkedorganization;type:uuid"` + + // norm core hours + NormCoreHours *int64 `json:"NormCoreHours,omitempty" gorm:"column:normcorehours;default:0"` + + // project contact email + // Format: email + ProjectContactEmail strfmt.Email `json:"ProjectContactEmail,omitempty" gorm:"column:projectcontactemail"` + + // project contact person + // Format: uuid + ProjectContactPerson strfmt.UUID `json:"ProjectContactPerson,omitempty" gorm:"column:projectcontactperson;type:uuid"` + + // project created by + // Format: uuid + ProjectCreatedBy strfmt.UUID `json:"ProjectCreatedBy,omitempty" gorm:"column:projectcreatedby;type:uuid"` + + // project creation time + // Format: date-time + ProjectCreationTime strfmt.DateTime `json:"ProjectCreationTime,omitempty" gorm:"column:projectcreationtime;type:timestamptz;default:now()"` + + // project description + ProjectDescription string `json:"ProjectDescription,omitempty" gorm:"column:projectdescription"` + + // project domain + ProjectDomain string `json:"ProjectDomain,omitempty" gorm:"column:projectdomain"` + + // project ID + // Format: uuid + ProjectID strfmt.UUID `json:"ProjectID,omitempty" gorm:"column:projectid;type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // project max price + ProjectMaxPrice *float64 `json:"ProjectMaxPrice,omitempty" gorm:"column:projectmaxprice;type:float8;default:0.0"` + + // project name + ProjectName string `json:"ProjectName,omitempty" gorm:"column:projectname"` + + // project short name + ProjectShortName string `json:"ProjectShortName,omitempty" gorm:"column:projectshortname;unique"` + + // project start date + // Format: date-time + ProjectStartDate strfmt.DateTime `json:"ProjectStartDate,omitempty" gorm:"column:projectstartdate;type:timestamptz"` + + // project status + // Enum: [PENDING ACTIVE DISABLED TERMINATED] + ProjectStatus string `json:"ProjectStatus,omitempty" gorm:"column:projectstatus"` + + // project termination date + // Format: date-time + ProjectTerminationDate strfmt.DateTime `json:"ProjectTerminationDate,omitempty" gorm:"column:projectterminationdate;type:timestamptz"` +} + +// Validate validates this project +func (m *Project) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateLinkedOrganization(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectContactEmail(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectContactPerson(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectCreatedBy(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectCreationTime(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectStartDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectStatus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProjectTerminationDate(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Project) validateLinkedOrganization(formats strfmt.Registry) error { + + if swag.IsZero(m.LinkedOrganization) { // not required + return nil + } + + if err := validate.FormatOf("LinkedOrganization", "body", "uuid", m.LinkedOrganization.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Project) validateProjectContactEmail(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectContactEmail) { // not required + return nil + } + + if err := validate.FormatOf("ProjectContactEmail", "body", "email", m.ProjectContactEmail.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Project) validateProjectContactPerson(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectContactPerson) { // not required + return nil + } + + if err := validate.FormatOf("ProjectContactPerson", "body", "uuid", m.ProjectContactPerson.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Project) validateProjectCreatedBy(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectCreatedBy) { // not required + return nil + } + + if err := validate.FormatOf("ProjectCreatedBy", "body", "uuid", m.ProjectCreatedBy.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Project) validateProjectCreationTime(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectCreationTime) { // not required + return nil + } + + if err := validate.FormatOf("ProjectCreationTime", "body", "date-time", m.ProjectCreationTime.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Project) validateProjectID(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectID) { // not required + return nil + } + + if err := validate.FormatOf("ProjectID", "body", "uuid", m.ProjectID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Project) validateProjectStartDate(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectStartDate) { // not required + return nil + } + + if err := validate.FormatOf("ProjectStartDate", "body", "date-time", m.ProjectStartDate.String(), formats); err != nil { + return err + } + + return nil +} + +var projectTypeProjectStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["PENDING","ACTIVE","DISABLED","TERMINATED"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + projectTypeProjectStatusPropEnum = append(projectTypeProjectStatusPropEnum, v) + } +} + +const ( + + // ProjectProjectStatusPENDING captures enum value "PENDING" + ProjectProjectStatusPENDING string = "PENDING" + + // ProjectProjectStatusACTIVE captures enum value "ACTIVE" + ProjectProjectStatusACTIVE string = "ACTIVE" + + // ProjectProjectStatusDISABLED captures enum value "DISABLED" + ProjectProjectStatusDISABLED string = "DISABLED" + + // ProjectProjectStatusTERMINATED captures enum value "TERMINATED" + ProjectProjectStatusTERMINATED string = "TERMINATED" +) + +// prop value enum +func (m *Project) validateProjectStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, projectTypeProjectStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Project) validateProjectStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectStatus) { // not required + return nil + } + + // value enum + if err := m.validateProjectStatusEnum("ProjectStatus", "body", m.ProjectStatus); err != nil { + return err + } + + return nil +} + +func (m *Project) validateProjectTerminationDate(formats strfmt.Registry) error { + + if swag.IsZero(m.ProjectTerminationDate) { // not required + return nil + } + + if err := validate.FormatOf("ProjectTerminationDate", "body", "date-time", m.ProjectTerminationDate.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Project) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Project) UnmarshalBinary(b []byte) error { + var res Project + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/extensions/lexis/models/status.go b/extensions/lexis/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/extensions/lexis/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/extensions/lexis/planManagerLoader.sh b/extensions/lexis/planManagerLoader.sh new file mode 100644 index 0000000..f7eba8a --- /dev/null +++ b/extensions/lexis/planManagerLoader.sh @@ -0,0 +1,64 @@ +#!/bin/bash + +SERVER="http://localhost" +API_KEY="1234567890abcdefghi" +API_VERSION="v1.0" + +# We load the plans +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/plan" -X POST -d '{ "id":"1", "name": "LEXIS_1", "offeredstartdate":"2019-01-01", "offeredenddate":"2040-12-31" }' + +# We load the skus +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "1", "name": "vcpu", "unit": "Core" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "2", "name": "ram", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "3", "name": "rootdisk", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "4", "name": "ephemeraldisk", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "5", "name": "floatingip", "unit": "IP" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "6", "name": "blockstorage", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "7", "name": "objectstorage", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "8", "name": "license", "unit": "License*Core" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "9", "name": "titanxp", "unit": "Core" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "10", "name": "t4", "unit": "Core" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "11", "name": "p100", "unit": "Core" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "12", "name": "rootdisk_ssd", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "13", "name": "ephemeraldisk_ssd", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "14", "name": "blockstorage_ssd", "unit": "GB" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "15", "name": "salomon", "unit": "core-hour" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "16", "name": "barbora", "unit": "core-hour" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "17", "name": "barbora-gpu", "unit": "core-hour" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku" -X POST -d '{ "id": "18", "name": "dgx", "unit": "core-hour" }' + +# We load the sku prices +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "1", "skuname": "vcpu", "unitprice": 0.000011574, "unit": "Core", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "2", "skuname": "ram", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "3", "skuname": "rootdisk", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "4", "skuname": "ephemeraldisk", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "5", "skuname": "floatingip", "unitprice": 0.000011574, "unit": "IP", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "6", "skuname": "blockstorage", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "7", "skuname": "objectstorage", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "8", "skuname": "license", "unitprice": 0.000011574, "unit": "License*Core", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "9", "skuname": "titanxp", "unitprice": 0.000011574, "unit": "Core", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "10", "skuname": "t4", "unitprice": 0.000011574, "unit": "Core", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "11", "skuname": "p100", "unitprice": 0.000011574, "unit": "Core", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "12", "skuname": "rootdisk_ssd", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "13", "skuname": "ephemeraldisk_ssd", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "14", "skuname": "blockstorage_ssd", "unitprice": 0.000011574, "unit": "GB", "planid": "1", "UnitCreditPrice": 0.000011574, "AccountingMode": "CASH" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "15", "skuname": "salomon", "unitprice": 0.000013889, "unit": "core-hour", "planid": "1", "UnitCreditPrice": 0.000013889, "AccountingMode": "CREDIT" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "16", "skuname": "barbora", "unitprice": 0.000020694, "unit": "core-hour", "planid": "1", "UnitCreditPrice": 0.000020694, "AccountingMode": "CREDIT" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "17", "skuname": "barbora-gpu", "unitprice": 0.000066111, "unit": "core-hour", "planid": "1", "UnitCreditPrice": 0.000066111, "AccountingMode": "CREDIT" }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/sku/price" -X POST -d '{ "skuid": "18", "skuname": "dgx", "unitprice": 0.000161667, "unit": "core-hour", "planid": "1", "UnitCreditPrice": 0.000161667, "AccountingMode": "CREDIT" }' + + +# We load the life cycles +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "active", "resourceType": "blockstorage", "skuList":{ "blockstorage": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "inactive", "resourceType": "blockstorage", "skuList":{ "blockstorage": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "active", "resourceType": "floatingip", "skuList":{ "floatingip": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "inactive", "resourceType": "floatingip", "skuList":{ "floatingip": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "used", "resourceType": "objectstorage", "skuList":{ "objectstorage": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "used", "resourceType": "salomon", "skuList":{ "salomon": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "used", "resourceType": "barbora", "skuList":{ "barbora": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "used", "resourceType": "barbora-gpu", "skuList":{ "barbora-gpu": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "used", "resourceType": "dgx", "skuList":{ "dgx": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "active", "resourceType": "server", "skuList":{ "vcpu": 1, "ram": 1, "titanxp": 1, "t4": 1, "p100": 1, "rootdisk": 1, "rootdisk_ssd": 1, "ephemeraldisk": 1, "ephemeraldisk_ssd": 1, "license": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "inactive", "resourceType": "server", "skuList":{ "titanxp": 1, "t4": 1, "p100": 1, "rootdisk": 1, "rootdisk_ssd": 1, "ephemeraldisk": 1, "ephemeraldisk_ssd": 1, "license": 1 } }' +curl --silent -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" "${SERVER}:8600/api/${API_VERSION}/cycle" -X POST -d '{ "state": "suspended", "resourceType": "server", "skuList":{ "ram": 1, "titanxp": 1, "t4": 1, "p100": 1, "rootdisk": 1, "rootdisk_ssd": 1, "ephemeraldisk": 1, "ephemeraldisk_ssd": 1, "license": 1 } }' + diff --git a/extensions/lexis/restapi/configure_l_e_x_i_s_extension_management_api.go b/extensions/lexis/restapi/configure_l_e_x_i_s_extension_management_api.go new file mode 100644 index 0000000..7fe9627 --- /dev/null +++ b/extensions/lexis/restapi/configure_l_e_x_i_s_extension_management_api.go @@ -0,0 +1,188 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/sync_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/trigger_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name SyncManagementAPI -inpkg + +/* SyncManagementAPI */ +type SyncManagementAPI interface { + /* SyncFlavors Sync the OpenStack's flavors data in the system */ + SyncFlavors(ctx context.Context, params sync_management.SyncFlavorsParams) middleware.Responder + + /* SyncHierarchy syncs all the organizations, projects, resources hierarchy from LEXIS */ + SyncHierarchy(ctx context.Context, params sync_management.SyncHierarchyParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* UDRRedo Redo of UDRs from the specific dates and with the specifc interval */ + UDRRedo(ctx context.Context, params trigger_management.UDRRedoParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + StatusManagementAPI + SyncManagementAPI + TriggerManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) + // Authenticator to use for all APIKey authentication + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // Authenticator to use for all Bearer authentication + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // Authenticator to use for all Basic authentication + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *LEXISExtensionManagementAPI instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.LEXISExtensionManagementAPIAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewLEXISExtensionManagementAPIAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + if c.APIKeyAuthenticator != nil { + api.APIKeyAuthenticator = c.APIKeyAuthenticator + } + if c.BasicAuthenticator != nil { + api.BasicAuthenticator = c.BasicAuthenticator + } + if c.BearerAuthenticator != nil { + api.BearerAuthenticator = c.BearerAuthenticator + } + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.TriggerManagementUDRRedoHandler = trigger_management.UDRRedoHandlerFunc(func(params trigger_management.UDRRedoParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.UDRRedo(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.SyncManagementSyncFlavorsHandler = sync_management.SyncFlavorsHandlerFunc(func(params sync_management.SyncFlavorsParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.SyncManagementAPI.SyncFlavors(ctx, params) + }) + api.SyncManagementSyncHierarchyHandler = sync_management.SyncHierarchyHandlerFunc(func(params sync_management.SyncHierarchyParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.SyncManagementAPI.SyncHierarchy(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/extensions/lexis/restapi/doc.go b/extensions/lexis/restapi/doc.go new file mode 100644 index 0000000..34f92f1 --- /dev/null +++ b/extensions/lexis/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi LEXIS Extension Management API +// +// An API which supports creation, deletion, listing etc of SERVICE +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v0.1 +// Version: 0.1.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/extensions/lexis/restapi/embedded_spec.go b/extensions/lexis/restapi/embedded_spec.go new file mode 100644 index 0000000..9150b4c --- /dev/null +++ b/extensions/lexis/restapi/embedded_spec.go @@ -0,0 +1,1102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of SERVICE", + "title": "LEXIS Extension Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "0.1.0" + }, + "host": "localhost:8000", + "basePath": "/api/v0.1", + "paths": { + "/status": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "metrics", + "sync" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sync/flavors": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "syncManagement" + ], + "summary": "Sync the OpenStack's flavors data in the system", + "operationId": "syncFlavors", + "responses": { + "200": { + "description": "The load of data was completely successfully" + }, + "202": { + "description": "Operation done but there might have been some fails when adding part of the data" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sync/hierarchy": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "syncManagement" + ], + "summary": "syncs all the organizations, projects, resources hierarchy from LEXIS", + "operationId": "syncHierarchy", + "responses": { + "200": { + "description": "The load of data was completely successfully" + }, + "202": { + "description": "Operation done but there might have been some fails when adding part of the data" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/udrsredo": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Redo of UDRs from the specific dates and with the specifc interval", + "operationId": "UDRRedo", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to regenerate the udrs", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to regenerate the udrs", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Interval to do increments", + "name": "interval", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Generation task executed successfully.", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "HPCResource": { + "type": "object", + "properties": { + "ApprovalStatus": { + "type": "string", + "enum": [ + "ACCEPTED", + "REJECTED", + "PENDING" + ], + "x-go-custom-tag": "gorm:\"column:approvalstatus\"" + }, + "AssociatedHPCProject": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:associatedhpcproject\"" + }, + "AssociatedLEXISProject": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:associatedlexisproject;type:uuid\"" + }, + "CloudNetworkName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:cloudnetworkname\"" + }, + "HEAppEEndpoint": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:heappeendpoint\"" + }, + "HPCProvider": { + "type": "string", + "enum": [ + "IT4I", + "LRZ", + "ICHEC" + ], + "x-go-custom-tag": "gorm:\"column:hpcprovider\"" + }, + "HPCResourceID": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:hpcresourceid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "OpenStackEndpoint": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:openstackendpoint\"" + }, + "OpenStackProjectID": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:openstackprojectid\"" + }, + "ProjectNetworkName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectnetworkname\"" + }, + "ResourceType": { + "type": "string", + "enum": [ + "CLOUD", + "HPC" + ], + "x-go-custom-tag": "gorm:\"column:resourcetype\"" + }, + "TermsConsent": { + "type": "boolean", + "x-go-custom-tag": "gorm:\"column:termsconsent;type:bool\"" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Organization": { + "type": "object", + "properties": { + "CreatedBy": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:createdby;type:uuid\"" + }, + "CreationDate": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:registrationdatetime;type:timestamptz\"" + }, + "FormalName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:formalname\"" + }, + "ID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "OrganizationEmailAddress": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"column:organizationemailaddress\"" + }, + "OrganizationStatus": { + "type": "string", + "enum": [ + "PENDING_APPROVAL", + "APPROVED", + "DISABLED", + "TERMINATED" + ], + "x-go-custom-tag": "gorm:\"column:organizationstatus\"" + }, + "PrimaryTelephoneNumber": { + "type": "string", + "format": "telephone-number", + "x-go-custom-tag": "gorm:\"column:primarytelephonenumber\"" + }, + "RegisteredAddress1": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:registeredaddress1\"" + }, + "RegisteredAddress2": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:registeredaddress2\"" + }, + "RegisteredAddress3": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:registeredaddress3\"" + }, + "RegisteredCountry": { + "type": "string", + "format": "country", + "x-go-custom-tag": "gorm:\"column:registeredcountry\"" + }, + "VATRegistrationNumber": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:vatregistrationnumber\"" + }, + "Website": { + "type": "string", + "format": "url" + } + } + }, + "Project": { + "type": "object", + "properties": { + "AllowedOrganizations": { + "x-go-custom-tag": "gorm:\"column:allowedorganizations;type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "LinkedOrganization": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:linkedorganization;type:uuid\"" + }, + "NormCoreHours": { + "type": "integer", + "default": 0, + "x-go-custom-tag": "gorm:\"column:normcorehours;default:0\"", + "x-nullable": true + }, + "ProjectContactEmail": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"column:projectcontactemail\"" + }, + "ProjectContactPerson": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:projectcontactperson;type:uuid\"" + }, + "ProjectCreatedBy": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:projectcreatedby;type:uuid\"" + }, + "ProjectCreationTime": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:projectcreationtime;type:timestamptz;default:now()\"" + }, + "ProjectDescription": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectdescription\"" + }, + "ProjectDomain": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectdomain\"" + }, + "ProjectID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:projectid;type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "ProjectMaxPrice": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"column:projectmaxprice;type:float8;default:0.0\"", + "x-nullable": true + }, + "ProjectName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectname\"" + }, + "ProjectShortName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectshortname;unique\"" + }, + "ProjectStartDate": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:projectstartdate;type:timestamptz\"" + }, + "ProjectStatus": { + "type": "string", + "enum": [ + "PENDING", + "ACTIVE", + "DISABLED", + "TERMINATED" + ], + "x-go-custom-tag": "gorm:\"column:projectstatus\"" + }, + "ProjectTerminationDate": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:projectterminationdate;type:timestamptz\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "StringArray": { + "x-go-type": { + "import": { + "package": "github.com/lib/pq" + }, + "type": "StringArray" + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the syncing of data from LEXIS into cyclops services.", + "name": "syncManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of SERVICE", + "title": "LEXIS Extension Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "0.1.0" + }, + "host": "localhost:8000", + "basePath": "/api/v0.1", + "paths": { + "/status": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "metrics", + "sync" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sync/flavors": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "syncManagement" + ], + "summary": "Sync the OpenStack's flavors data in the system", + "operationId": "syncFlavors", + "responses": { + "200": { + "description": "The load of data was completely successfully" + }, + "202": { + "description": "Operation done but there might have been some fails when adding part of the data" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sync/hierarchy": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "syncManagement" + ], + "summary": "syncs all the organizations, projects, resources hierarchy from LEXIS", + "operationId": "syncHierarchy", + "responses": { + "200": { + "description": "The load of data was completely successfully" + }, + "202": { + "description": "Operation done but there might have been some fails when adding part of the data" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/udrsredo": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Redo of UDRs from the specific dates and with the specifc interval", + "operationId": "UDRRedo", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to regenerate the udrs", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to regenerate the udrs", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Interval to do increments", + "name": "interval", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Generation task executed successfully.", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "HPCResource": { + "type": "object", + "properties": { + "ApprovalStatus": { + "type": "string", + "enum": [ + "ACCEPTED", + "REJECTED", + "PENDING" + ], + "x-go-custom-tag": "gorm:\"column:approvalstatus\"" + }, + "AssociatedHPCProject": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:associatedhpcproject\"" + }, + "AssociatedLEXISProject": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:associatedlexisproject;type:uuid\"" + }, + "CloudNetworkName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:cloudnetworkname\"" + }, + "HEAppEEndpoint": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:heappeendpoint\"" + }, + "HPCProvider": { + "type": "string", + "enum": [ + "IT4I", + "LRZ", + "ICHEC" + ], + "x-go-custom-tag": "gorm:\"column:hpcprovider\"" + }, + "HPCResourceID": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:hpcresourceid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "OpenStackEndpoint": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:openstackendpoint\"" + }, + "OpenStackProjectID": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:openstackprojectid\"" + }, + "ProjectNetworkName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectnetworkname\"" + }, + "ResourceType": { + "type": "string", + "enum": [ + "CLOUD", + "HPC" + ], + "x-go-custom-tag": "gorm:\"column:resourcetype\"" + }, + "TermsConsent": { + "type": "boolean", + "x-go-custom-tag": "gorm:\"column:termsconsent;type:bool\"" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Organization": { + "type": "object", + "properties": { + "CreatedBy": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:createdby;type:uuid\"" + }, + "CreationDate": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:registrationdatetime;type:timestamptz\"" + }, + "FormalName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:formalname\"" + }, + "ID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "OrganizationEmailAddress": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"column:organizationemailaddress\"" + }, + "OrganizationStatus": { + "type": "string", + "enum": [ + "PENDING_APPROVAL", + "APPROVED", + "DISABLED", + "TERMINATED" + ], + "x-go-custom-tag": "gorm:\"column:organizationstatus\"" + }, + "PrimaryTelephoneNumber": { + "type": "string", + "format": "telephone-number", + "x-go-custom-tag": "gorm:\"column:primarytelephonenumber\"" + }, + "RegisteredAddress1": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:registeredaddress1\"" + }, + "RegisteredAddress2": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:registeredaddress2\"" + }, + "RegisteredAddress3": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:registeredaddress3\"" + }, + "RegisteredCountry": { + "type": "string", + "format": "country", + "x-go-custom-tag": "gorm:\"column:registeredcountry\"" + }, + "VATRegistrationNumber": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:vatregistrationnumber\"" + }, + "Website": { + "type": "string", + "format": "url" + } + } + }, + "Project": { + "type": "object", + "properties": { + "AllowedOrganizations": { + "x-go-custom-tag": "gorm:\"column:allowedorganizations;type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "LinkedOrganization": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:linkedorganization;type:uuid\"" + }, + "NormCoreHours": { + "type": "integer", + "default": 0, + "x-go-custom-tag": "gorm:\"column:normcorehours;default:0\"", + "x-nullable": true + }, + "ProjectContactEmail": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"column:projectcontactemail\"" + }, + "ProjectContactPerson": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:projectcontactperson;type:uuid\"" + }, + "ProjectCreatedBy": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:projectcreatedby;type:uuid\"" + }, + "ProjectCreationTime": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:projectcreationtime;type:timestamptz;default:now()\"" + }, + "ProjectDescription": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectdescription\"" + }, + "ProjectDomain": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectdomain\"" + }, + "ProjectID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"column:projectid;type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "ProjectMaxPrice": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"column:projectmaxprice;type:float8;default:0.0\"", + "x-nullable": true + }, + "ProjectName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectname\"" + }, + "ProjectShortName": { + "type": "string", + "x-go-custom-tag": "gorm:\"column:projectshortname;unique\"" + }, + "ProjectStartDate": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:projectstartdate;type:timestamptz\"" + }, + "ProjectStatus": { + "type": "string", + "enum": [ + "PENDING", + "ACTIVE", + "DISABLED", + "TERMINATED" + ], + "x-go-custom-tag": "gorm:\"column:projectstatus\"" + }, + "ProjectTerminationDate": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"column:projectterminationdate;type:timestamptz\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "StringArray": { + "x-go-type": { + "import": { + "package": "github.com/lib/pq" + }, + "type": "StringArray" + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "admin", + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the syncing of data from LEXIS into cyclops services.", + "name": "syncManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + } + ] +}`)) +} diff --git a/extensions/lexis/restapi/operations/l_e_x_i_s_extension_management_api_api.go b/extensions/lexis/restapi/operations/l_e_x_i_s_extension_management_api_api.go new file mode 100644 index 0000000..d51a04e --- /dev/null +++ b/extensions/lexis/restapi/operations/l_e_x_i_s_extension_management_api_api.go @@ -0,0 +1,405 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/sync_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/trigger_management" +) + +// NewLEXISExtensionManagementAPIAPI creates a new LEXISExtensionManagementAPI instance +func NewLEXISExtensionManagementAPIAPI(spec *loads.Document) *LEXISExtensionManagementAPIAPI { + return &LEXISExtensionManagementAPIAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + useSwaggerUI: false, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + TriggerManagementUDRRedoHandler: trigger_management.UDRRedoHandlerFunc(func(params trigger_management.UDRRedoParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.UDRRedo has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + SyncManagementSyncFlavorsHandler: sync_management.SyncFlavorsHandlerFunc(func(params sync_management.SyncFlavorsParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation sync_management.SyncFlavors has not yet been implemented") + }), + SyncManagementSyncHierarchyHandler: sync_management.SyncHierarchyHandlerFunc(func(params sync_management.SyncHierarchyParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation sync_management.SyncHierarchy has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*LEXISExtensionManagementAPIAPI An API which supports creation, deletion, listing etc of SERVICE */ +type LEXISExtensionManagementAPIAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + useSwaggerUI bool + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // TriggerManagementUDRRedoHandler sets the operation handler for the u d r redo operation + TriggerManagementUDRRedoHandler trigger_management.UDRRedoHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // SyncManagementSyncFlavorsHandler sets the operation handler for the sync flavors operation + SyncManagementSyncFlavorsHandler sync_management.SyncFlavorsHandler + // SyncManagementSyncHierarchyHandler sets the operation handler for the sync hierarchy operation + SyncManagementSyncHierarchyHandler sync_management.SyncHierarchyHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// UseRedoc for documentation at /docs +func (o *LEXISExtensionManagementAPIAPI) UseRedoc() { + o.useSwaggerUI = false +} + +// UseSwaggerUI for documentation at /docs +func (o *LEXISExtensionManagementAPIAPI) UseSwaggerUI() { + o.useSwaggerUI = true +} + +// SetDefaultProduces sets the default produces media type +func (o *LEXISExtensionManagementAPIAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *LEXISExtensionManagementAPIAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *LEXISExtensionManagementAPIAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *LEXISExtensionManagementAPIAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *LEXISExtensionManagementAPIAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *LEXISExtensionManagementAPIAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *LEXISExtensionManagementAPIAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the LEXISExtensionManagementAPIAPI +func (o *LEXISExtensionManagementAPIAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.TriggerManagementUDRRedoHandler == nil { + unregistered = append(unregistered, "trigger_management.UDRRedoHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + if o.SyncManagementSyncFlavorsHandler == nil { + unregistered = append(unregistered, "sync_management.SyncFlavorsHandler") + } + if o.SyncManagementSyncHierarchyHandler == nil { + unregistered = append(unregistered, "sync_management.SyncHierarchyHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *LEXISExtensionManagementAPIAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *LEXISExtensionManagementAPIAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *LEXISExtensionManagementAPIAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *LEXISExtensionManagementAPIAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *LEXISExtensionManagementAPIAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *LEXISExtensionManagementAPIAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the l e x i s extension management API API +func (o *LEXISExtensionManagementAPIAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *LEXISExtensionManagementAPIAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/udrsredo"] = trigger_management.NewUDRRedo(o.context, o.TriggerManagementUDRRedoHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sync/flavors"] = sync_management.NewSyncFlavors(o.context, o.SyncManagementSyncFlavorsHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sync/hierarchy"] = sync_management.NewSyncHierarchy(o.context, o.SyncManagementSyncHierarchyHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *LEXISExtensionManagementAPIAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + if o.useSwaggerUI { + return o.context.APIHandlerSwaggerUI(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *LEXISExtensionManagementAPIAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *LEXISExtensionManagementAPIAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *LEXISExtensionManagementAPIAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *LEXISExtensionManagementAPIAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/extensions/lexis/restapi/operations/status_management/get_status.go b/extensions/lexis/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/extensions/lexis/restapi/operations/status_management/get_status_parameters.go b/extensions/lexis/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..983df18 --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the endpoint to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"kafka-receiver", "kafka-sender", "status", "trigger", "metrics", "sync"}, true); err != nil { + return err + } + + return nil +} diff --git a/extensions/lexis/restapi/operations/status_management/get_status_responses.go b/extensions/lexis/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..f8e6b82 --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/extensions/lexis/restapi/operations/status_management/get_status_urlbuilder.go b/extensions/lexis/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..a9ea261 --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v0.1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/extensions/lexis/restapi/operations/status_management/show_status.go b/extensions/lexis/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/extensions/lexis/restapi/operations/status_management/show_status_parameters.go b/extensions/lexis/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/restapi/operations/status_management/show_status_responses.go b/extensions/lexis/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..5b0549b --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/extensions/lexis/restapi/operations/status_management/show_status_urlbuilder.go b/extensions/lexis/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..06b97e1 --- /dev/null +++ b/extensions/lexis/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v0.1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_flavors.go b/extensions/lexis/restapi/operations/sync_management/sync_flavors.go new file mode 100644 index 0000000..6ceb45b --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_flavors.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// SyncFlavorsHandlerFunc turns a function with the right signature into a sync flavors handler +type SyncFlavorsHandlerFunc func(SyncFlavorsParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn SyncFlavorsHandlerFunc) Handle(params SyncFlavorsParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// SyncFlavorsHandler interface for that can handle valid sync flavors params +type SyncFlavorsHandler interface { + Handle(SyncFlavorsParams, interface{}) middleware.Responder +} + +// NewSyncFlavors creates a new http.Handler for the sync flavors operation +func NewSyncFlavors(ctx *middleware.Context, handler SyncFlavorsHandler) *SyncFlavors { + return &SyncFlavors{Context: ctx, Handler: handler} +} + +/*SyncFlavors swagger:route GET /sync/flavors syncManagement syncFlavors + +Sync the OpenStack's flavors data in the system + +*/ +type SyncFlavors struct { + Context *middleware.Context + Handler SyncFlavorsHandler +} + +func (o *SyncFlavors) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewSyncFlavorsParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_flavors_parameters.go b/extensions/lexis/restapi/operations/sync_management/sync_flavors_parameters.go new file mode 100644 index 0000000..da42b5e --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_flavors_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewSyncFlavorsParams creates a new SyncFlavorsParams object +// no default values defined in spec. +func NewSyncFlavorsParams() SyncFlavorsParams { + + return SyncFlavorsParams{} +} + +// SyncFlavorsParams contains all the bound params for the sync flavors operation +// typically these are obtained from a http.Request +// +// swagger:parameters syncFlavors +type SyncFlavorsParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewSyncFlavorsParams() beforehand. +func (o *SyncFlavorsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_flavors_responses.go b/extensions/lexis/restapi/operations/sync_management/sync_flavors_responses.go new file mode 100644 index 0000000..4c1acc0 --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_flavors_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// SyncFlavorsOKCode is the HTTP code returned for type SyncFlavorsOK +const SyncFlavorsOKCode int = 200 + +/*SyncFlavorsOK The load of data was completely successfully + +swagger:response syncFlavorsOK +*/ +type SyncFlavorsOK struct { +} + +// NewSyncFlavorsOK creates SyncFlavorsOK with default headers values +func NewSyncFlavorsOK() *SyncFlavorsOK { + + return &SyncFlavorsOK{} +} + +// WriteResponse to the client +func (o *SyncFlavorsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// SyncFlavorsAcceptedCode is the HTTP code returned for type SyncFlavorsAccepted +const SyncFlavorsAcceptedCode int = 202 + +/*SyncFlavorsAccepted Operation done but there might have been some fails when adding part of the data + +swagger:response syncFlavorsAccepted +*/ +type SyncFlavorsAccepted struct { +} + +// NewSyncFlavorsAccepted creates SyncFlavorsAccepted with default headers values +func NewSyncFlavorsAccepted() *SyncFlavorsAccepted { + + return &SyncFlavorsAccepted{} +} + +// WriteResponse to the client +func (o *SyncFlavorsAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(202) +} + +// SyncFlavorsInternalServerErrorCode is the HTTP code returned for type SyncFlavorsInternalServerError +const SyncFlavorsInternalServerErrorCode int = 500 + +/*SyncFlavorsInternalServerError Something unexpected happend, error raised + +swagger:response syncFlavorsInternalServerError +*/ +type SyncFlavorsInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewSyncFlavorsInternalServerError creates SyncFlavorsInternalServerError with default headers values +func NewSyncFlavorsInternalServerError() *SyncFlavorsInternalServerError { + + return &SyncFlavorsInternalServerError{} +} + +// WithPayload adds the payload to the sync flavors internal server error response +func (o *SyncFlavorsInternalServerError) WithPayload(payload *models.ErrorResponse) *SyncFlavorsInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the sync flavors internal server error response +func (o *SyncFlavorsInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *SyncFlavorsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_flavors_urlbuilder.go b/extensions/lexis/restapi/operations/sync_management/sync_flavors_urlbuilder.go new file mode 100644 index 0000000..cca7876 --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_flavors_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// SyncFlavorsURL generates an URL for the sync flavors operation +type SyncFlavorsURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *SyncFlavorsURL) WithBasePath(bp string) *SyncFlavorsURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *SyncFlavorsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *SyncFlavorsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sync/flavors" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v0.1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *SyncFlavorsURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *SyncFlavorsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *SyncFlavorsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on SyncFlavorsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on SyncFlavorsURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *SyncFlavorsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_hierarchy.go b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy.go new file mode 100644 index 0000000..510f52f --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// SyncHierarchyHandlerFunc turns a function with the right signature into a sync hierarchy handler +type SyncHierarchyHandlerFunc func(SyncHierarchyParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn SyncHierarchyHandlerFunc) Handle(params SyncHierarchyParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// SyncHierarchyHandler interface for that can handle valid sync hierarchy params +type SyncHierarchyHandler interface { + Handle(SyncHierarchyParams, interface{}) middleware.Responder +} + +// NewSyncHierarchy creates a new http.Handler for the sync hierarchy operation +func NewSyncHierarchy(ctx *middleware.Context, handler SyncHierarchyHandler) *SyncHierarchy { + return &SyncHierarchy{Context: ctx, Handler: handler} +} + +/*SyncHierarchy swagger:route GET /sync/hierarchy syncManagement syncHierarchy + +syncs all the organizations, projects, resources hierarchy from LEXIS + +*/ +type SyncHierarchy struct { + Context *middleware.Context + Handler SyncHierarchyHandler +} + +func (o *SyncHierarchy) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewSyncHierarchyParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_parameters.go b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_parameters.go new file mode 100644 index 0000000..a29835f --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewSyncHierarchyParams creates a new SyncHierarchyParams object +// no default values defined in spec. +func NewSyncHierarchyParams() SyncHierarchyParams { + + return SyncHierarchyParams{} +} + +// SyncHierarchyParams contains all the bound params for the sync hierarchy operation +// typically these are obtained from a http.Request +// +// swagger:parameters syncHierarchy +type SyncHierarchyParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewSyncHierarchyParams() beforehand. +func (o *SyncHierarchyParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_responses.go b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_responses.go new file mode 100644 index 0000000..3b413d6 --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// SyncHierarchyOKCode is the HTTP code returned for type SyncHierarchyOK +const SyncHierarchyOKCode int = 200 + +/*SyncHierarchyOK The load of data was completely successfully + +swagger:response syncHierarchyOK +*/ +type SyncHierarchyOK struct { +} + +// NewSyncHierarchyOK creates SyncHierarchyOK with default headers values +func NewSyncHierarchyOK() *SyncHierarchyOK { + + return &SyncHierarchyOK{} +} + +// WriteResponse to the client +func (o *SyncHierarchyOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// SyncHierarchyAcceptedCode is the HTTP code returned for type SyncHierarchyAccepted +const SyncHierarchyAcceptedCode int = 202 + +/*SyncHierarchyAccepted Operation done but there might have been some fails when adding part of the data + +swagger:response syncHierarchyAccepted +*/ +type SyncHierarchyAccepted struct { +} + +// NewSyncHierarchyAccepted creates SyncHierarchyAccepted with default headers values +func NewSyncHierarchyAccepted() *SyncHierarchyAccepted { + + return &SyncHierarchyAccepted{} +} + +// WriteResponse to the client +func (o *SyncHierarchyAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(202) +} + +// SyncHierarchyInternalServerErrorCode is the HTTP code returned for type SyncHierarchyInternalServerError +const SyncHierarchyInternalServerErrorCode int = 500 + +/*SyncHierarchyInternalServerError Something unexpected happend, error raised + +swagger:response syncHierarchyInternalServerError +*/ +type SyncHierarchyInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewSyncHierarchyInternalServerError creates SyncHierarchyInternalServerError with default headers values +func NewSyncHierarchyInternalServerError() *SyncHierarchyInternalServerError { + + return &SyncHierarchyInternalServerError{} +} + +// WithPayload adds the payload to the sync hierarchy internal server error response +func (o *SyncHierarchyInternalServerError) WithPayload(payload *models.ErrorResponse) *SyncHierarchyInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the sync hierarchy internal server error response +func (o *SyncHierarchyInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *SyncHierarchyInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_urlbuilder.go b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_urlbuilder.go new file mode 100644 index 0000000..7cea757 --- /dev/null +++ b/extensions/lexis/restapi/operations/sync_management/sync_hierarchy_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sync_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// SyncHierarchyURL generates an URL for the sync hierarchy operation +type SyncHierarchyURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *SyncHierarchyURL) WithBasePath(bp string) *SyncHierarchyURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *SyncHierarchyURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *SyncHierarchyURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sync/hierarchy" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v0.1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *SyncHierarchyURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *SyncHierarchyURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *SyncHierarchyURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on SyncHierarchyURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on SyncHierarchyURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *SyncHierarchyURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo.go b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo.go new file mode 100644 index 0000000..7d9d498 --- /dev/null +++ b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UDRRedoHandlerFunc turns a function with the right signature into a u d r redo handler +type UDRRedoHandlerFunc func(UDRRedoParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UDRRedoHandlerFunc) Handle(params UDRRedoParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UDRRedoHandler interface for that can handle valid u d r redo params +type UDRRedoHandler interface { + Handle(UDRRedoParams, interface{}) middleware.Responder +} + +// NewUDRRedo creates a new http.Handler for the u d r redo operation +func NewUDRRedo(ctx *middleware.Context, handler UDRRedoHandler) *UDRRedo { + return &UDRRedo{Context: ctx, Handler: handler} +} + +/*UDRRedo swagger:route GET /trigger/udrsredo triggerManagement uDRRedo + +Redo of UDRs from the specific dates and with the specifc interval + +*/ +type UDRRedo struct { + Context *middleware.Context + Handler UDRRedoHandler +} + +func (o *UDRRedo) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUDRRedoParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_parameters.go b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_parameters.go new file mode 100644 index 0000000..a87ce46 --- /dev/null +++ b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_parameters.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewUDRRedoParams creates a new UDRRedoParams object +// no default values defined in spec. +func NewUDRRedoParams() UDRRedoParams { + + return UDRRedoParams{} +} + +// UDRRedoParams contains all the bound params for the u d r redo operation +// typically these are obtained from a http.Request +// +// swagger:parameters UDRRedo +type UDRRedoParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to regenerate the udrs + In: query + */ + From *strfmt.DateTime + /*Interval to do increments + In: query + */ + Interval *string + /*Datetime until which to regenerate the udrs + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUDRRedoParams() beforehand. +func (o *UDRRedoParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + qInterval, qhkInterval, _ := qs.GetOK("interval") + if err := o.bindInterval(qInterval, qhkInterval, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *UDRRedoParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *UDRRedoParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindInterval binds and validates parameter Interval from query. +func (o *UDRRedoParams) bindInterval(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Interval = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *UDRRedoParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *UDRRedoParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_responses.go b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_responses.go new file mode 100644 index 0000000..3a002c6 --- /dev/null +++ b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" +) + +// UDRRedoOKCode is the HTTP code returned for type UDRRedoOK +const UDRRedoOKCode int = 200 + +/*UDRRedoOK Generation task executed successfully. + +swagger:response uDRRedoOK +*/ +type UDRRedoOK struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewUDRRedoOK creates UDRRedoOK with default headers values +func NewUDRRedoOK() *UDRRedoOK { + + return &UDRRedoOK{} +} + +// WithPayload adds the payload to the u d r redo o k response +func (o *UDRRedoOK) WithPayload(payload *models.ItemCreatedResponse) *UDRRedoOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the u d r redo o k response +func (o *UDRRedoOK) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UDRRedoOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UDRRedoInternalServerErrorCode is the HTTP code returned for type UDRRedoInternalServerError +const UDRRedoInternalServerErrorCode int = 500 + +/*UDRRedoInternalServerError Something unexpected happend, error raised + +swagger:response uDRRedoInternalServerError +*/ +type UDRRedoInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUDRRedoInternalServerError creates UDRRedoInternalServerError with default headers values +func NewUDRRedoInternalServerError() *UDRRedoInternalServerError { + + return &UDRRedoInternalServerError{} +} + +// WithPayload adds the payload to the u d r redo internal server error response +func (o *UDRRedoInternalServerError) WithPayload(payload *models.ErrorResponse) *UDRRedoInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the u d r redo internal server error response +func (o *UDRRedoInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UDRRedoInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_urlbuilder.go b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_urlbuilder.go new file mode 100644 index 0000000..9e6ef59 --- /dev/null +++ b/extensions/lexis/restapi/operations/trigger_management/u_d_r_redo_urlbuilder.go @@ -0,0 +1,123 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/strfmt" +) + +// UDRRedoURL generates an URL for the u d r redo operation +type UDRRedoURL struct { + From *strfmt.DateTime + Interval *string + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UDRRedoURL) WithBasePath(bp string) *UDRRedoURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UDRRedoURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UDRRedoURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/udrsredo" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v0.1" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var intervalQ string + if o.Interval != nil { + intervalQ = *o.Interval + } + if intervalQ != "" { + qs.Set("interval", intervalQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UDRRedoURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UDRRedoURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UDRRedoURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UDRRedoURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UDRRedoURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UDRRedoURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/extensions/lexis/restapi/server.go b/extensions/lexis/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/extensions/lexis/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/extensions/lexis/run/cert.crt b/extensions/lexis/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/extensions/lexis/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/extensions/lexis/run/config.toml b/extensions/lexis/run/config.toml new file mode 100644 index 0000000..ad02e9c --- /dev/null +++ b/extensions/lexis/run/config.toml @@ -0,0 +1,86 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "24h" + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +LogFile = "./SERVICE.log" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8001" +CDR = "cdr:8002" +CreditSystem = "creditsystem:8003" +CustomerDB = "customerdb:8004" +EventsEngine = "eventsengine:8005" +PlanManager = "planmanager:8006" +UDR = "udr:8007" + +[KEYCLOAK] +ClientID = "CyclopsDeploy" +ClientSecret = "093d537e-205e-4a4c-94c6-3d9b744e2675" +Enabled = true +Host = "keycloak" +Port = 8000 +Realm = "Development" +RedirectURL = "" +UseHttp = true + +[OPENSTACK] +Domain = "" +Filters = [ "filter1", "filter2", "filter3" ] +Keystone = "" +Password = "" +Project = "" +Regions = [ "Region1", "Region2" ] +User = "" + +[SKUS] +SKUs = [ "vcpu", "ram", "rootdisk", "ephemeraldisk", "floatingip", "blockstorage", "objectstorage", "license", "titanxp", "t4", "p100", "rootdisk_ssd", "ephemeraldisk_ssd", "blockstorage_ssd" ] + +[PRICES] +BLOCKSTORAGE = 0 +BLOCKSTORAGE_SSD = 0 +EPHEMERALDISK = 0 +EPHEMERALDISK_SSD = 0 +FLOATINGIP = 0 +LICENSE = 0 +OBJECTSTORAGE = 0 +RAM = 0 +ROOTDISK = 0 +ROOTDISK_SSD = 0 +VCPU = 0 diff --git a/extensions/lexis/run/docker-compose.yml b/extensions/lexis/run/docker-compose.yml new file mode 100644 index 0000000..042a2c2 --- /dev/null +++ b/extensions/lexis/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: lexis-extension:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/extensions/lexis/run/key.key b/extensions/lexis/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/extensions/lexis/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/extensions/lexis/server/cache.go b/extensions/lexis/server/cache.go new file mode 100644 index 0000000..4a7c25c --- /dev/null +++ b/extensions/lexis/server/cache.go @@ -0,0 +1,553 @@ +package main + +import ( + "context" + "net/url" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/cacheManager" + cdrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client" + cdrUsage "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/usage_management" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + cusCustomer "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/customer_management" + cusProduct "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/product_management" + cusReseller "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/reseller_management" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + pmBundle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/bundle_management" + pmCycle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/cycle_management" + pmPlan "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/plan_management" + pmSku "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/sku_management" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheStart handles the initialization of the cache mechanism service. +// Returns: +// - A cacheManager reference struct already initialized and ready to be used. +func cacheStart(metrics *prometheus.GaugeVec) *cacheManager.CacheManager { + + l.Trace.Printf("[CACHE][INIT] Intializing cache mechanism.\n") + + cacheDuration, _ := time.ParseDuration(cfg.DB.CacheRetention) + + c := cacheManager.New(metrics, cacheDuration, cfg.APIKey.Token) + + resellerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusReseller.NewGetResellerParams().WithID(i) + + r, e := client.ResellerManagement.GetReseller(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the reseller with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusReseller.NewListResellersParams() + + r, e := client.ResellerManagement.ListResellers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of resellers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + customerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusCustomer.NewGetCustomerParams().WithID(i) + + r, e := client.CustomerManagement.GetCustomer(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the customer with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusCustomer.NewListCustomersParams() + + r, e := client.CustomerManagement.ListCustomers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of customers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + productFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusProduct.NewGetProductParams().WithID(i) + + r, e := client.ProductManagement.GetProduct(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the product with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusProduct.NewListProductsParams() + + r, e := client.ProductManagement.ListProducts(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of products. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + // id == id0[,id1,...,idN]?from?to + cdrFunction := func(id interface{}, token string) (interface{}, error) { + + config := cdrClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["cdr"], + Path: cdrClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + idSplit := strings.SplitN(id.(string), "?", 3) + + i := idSplit[0] + + from, e := time.Parse(time.RFC3339Nano, idSplit[1]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[1], e) + + return nil, e + + } + + f := (strfmt.DateTime)(from) + + to, e := time.Parse(time.RFC3339Nano, idSplit[2]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[2], e) + + return nil, e + + } + + t := (strfmt.DateTime)(to) + + client := cdrClient.New(config) + ctx := context.Background() + + if strings.Contains(i, ",") { + + params := cdrUsage.NewGetSystemUsageParams().WithIdlist(&i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + if i != "ALL" { + + params := cdrUsage.NewGetUsageParams().WithID(i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving the CDRs under the id [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := cdrUsage.NewGetSystemUsageParams().WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + skuFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmSku.NewGetSkuParams().WithID(id.(string)) + + r, e := client.SkuManagement.GetSku(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the sku [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := pmSku.NewListSkusParams() + + r, e := client.SkuManagement.ListSkus(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the skus list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + planFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + var planID string + + if id.(string) == "DEFAULT" { + + planID = cfg.Plans.Default + + } else { + + planID = id.(string) + + } + + params := pmPlan.NewGetCompletePlanParams().WithID(planID) + + r, e := client.PlanManagement.GetCompletePlan(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmPlan.NewListCompletePlansParams() + + r, e := client.PlanManagement.ListCompletePlans(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + bundleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmBundle.NewGetSkuBundleParams().WithID(id.(string)) + + r, e := client.BundleManagement.GetSkuBundle(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmBundle.NewListSkuBundlesParams() + + r, e := client.BundleManagement.ListSkuBundles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + cycleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + var params *pmCycle.ListCyclesParams + + if id.(string) == "ALL" { + + params = pmCycle.NewListCyclesParams() + + } else { + + ty := id.(string) + + params = pmCycle.NewListCyclesParams().WithType(&ty) + + } + + r, e := client.CycleManagement.ListCycles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CYCLE-FUNCTION] There was a problem while retrieving the cycle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + c.Add("reseller", resellerFunction) + l.Trace.Printf("[CACHE][INIT] Reseller fetcher added to the cache.\n") + + c.Add("customer", customerFunction) + l.Trace.Printf("[CACHE][INIT] Customer fetcher added to the cache.\n") + + c.Add("product", productFunction) + l.Trace.Printf("[CACHE][INIT] Product fetcher added to the cache.\n") + + c.Add("cdr", cdrFunction) + l.Trace.Printf("[CACHE][INIT] CDR usage fetcher added to the cache.\n") + + c.Add("sku", skuFunction) + l.Trace.Printf("[CACHE][INIT] SKU fetcher added to the cache.\n") + + c.Add("plan", planFunction) + l.Trace.Printf("[CACHE][INIT] Plan fetcher added to the cache.\n") + + c.Add("bundle", bundleFunction) + l.Trace.Printf("[CACHE][INIT] SkuBundle fetcher added to the cache.\n") + + c.Add("cycle", cycleFunction) + l.Trace.Printf("[CACHE][INIT] Life Cycle fetcher added to the cache.\n") + + return c + +} diff --git a/extensions/lexis/server/cacheManager/cacheManager.go b/extensions/lexis/server/cacheManager/cacheManager.go new file mode 100644 index 0000000..ef0cf31 --- /dev/null +++ b/extensions/lexis/server/cacheManager/cacheManager.go @@ -0,0 +1,281 @@ +package cacheManager + +import ( + "fmt" + "strings" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheFetchFunction it will need the id to retrieve and as and option a Bearer +// Keycloak token can be provided when called. +// It shall return the object and errors in case of problems. +type cacheFetchFunction func(interface{}, string) (interface{}, error) + +// cache struct is the main "object" which handles the cache and its items. +// It also contains a map with the conversions of interfaces to strings. +type cache struct { + ////conversionDictionary map[string]string + data map[string]*cacheItem + fetchers map[string]cacheFetchFunction + mutex sync.RWMutex +} + +// cacheItem struct referes to the data of each element saved in the cache. +type cacheItem struct { + fetcher cacheFetchFunction + lastUpdate time.Time + value interface{} +} + +// CacheManager is the struct defined to group and contain all the methods +// that interact with the caching mechanism. +type CacheManager struct { + APIKey string + duration time.Duration + metrics *prometheus.GaugeVec + store cache +} + +// New is the function to create the struct CacheManager. +// Parameters: +// - t: a time.Duration with the max duration alive of the cache elements. +// - k: string containing the APIKey/token in case of need. +// Returns: +// - CacheManager: struct to interact with CacheManager subsystem functionalities. +func New(metrics *prometheus.GaugeVec, t time.Duration, k string) *CacheManager { + + l.Trace.Printf("[CACHE] Initializing the cache service.\n") + + c := CacheManager{ + APIKey: k, + duration: t, + metrics: metrics, + store: cache{ + data: make(map[string]*cacheItem), + fetchers: make(map[string]cacheFetchFunction), + }, + } + + return &c + +} + +// Add function job is to insert a new model in the cache. +// What it does is link the model with a fetching function and, if wanted, with +// a plain text name, so later in order to retrieve things from the cache they +// can be refereced either by the struct model or the plain text name. +// Paramenters: +// - plainName: a case insensitive name/alias to retrieve the data. +// - fetcher: the cacheFetchFunction used to retrieve the data. +func (c *CacheManager) Add(plainName string, fetcher cacheFetchFunction) { + + l.Trace.Printf("[CACHE] Adding a new object fetcher in the cache.\n") + + key := strings.ToUpper(plainName) + + c.store.mutex.Lock() + + c.store.fetchers[key] = fetcher + + c.store.mutex.Unlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Models in Cache"}).Inc() + + return + +} + +// fetch function job is to retrieve a new and updated copy of the remote object. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) fetch(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + c.store.mutex.RLock() + + object := c.store.data[item] + + c.store.mutex.RUnlock() + + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := object.fetcher(id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + object.value = uValue + object.lastUpdate = time.Now() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// fetch function job is to create the new item in the cache and retrieve a new +// and updated initial copy of the remote object to be saved in the cache. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) init(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + key := strings.Split(item, "-")[0] + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := c.store.fetchers[key](id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + i := cacheItem{ + fetcher: c.store.fetchers[key], + lastUpdate: time.Now(), + value: uValue, + } + + c.store.mutex.Lock() + + c.store.data[item] = &i + + c.store.mutex.Unlock() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// key is a function to ensure that the creation of the the item key for the +// cache is consistent across all the functions. +// Paramenters: +// - id: the reference id of the object to be retrieved +// - model: the alias text used to identify the source of objects. +// Returns: +// - s: the key string +func (c *CacheManager) key(id interface{}, model string) (s string) { + + s = fmt.Sprintf("%v-%v", strings.ToUpper(model), id) + + return + +} + +// Get function job is to retrieve an object from the cache or fetch it from the +// source and upgrade the copy in the cache in case the expiration time has been +// exceeded. +// Paramenters: +// - id: the reference id of the object. +// - model: the text alias set to reference the model. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - The object associated with the request +// - An error raised in case something went wrong while retrieving the object. +func (c *CacheManager) Get(id interface{}, model string, token string) (interface{}, error) { + + l.Trace.Printf("[CACHE] Retrieving object [ %v, %v ] from the cache.\n", id, model) + + item := c.key(id, model) + + c.store.mutex.RLock() + + object, exists := c.store.data[item] + + c.store.mutex.RUnlock() + + if !exists { + + l.Trace.Printf("[CACHE] Object [ %v ] first time requested, including in the cache.\n", item) + + if e := c.init(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while adding the new item [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects cached"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects cached"}).Inc() + + return o, nil + + } + + l.Trace.Printf("[CACHE] Object [ %v ] exists in the cache.\n", item) + + c.store.mutex.RLock() + + diff := (time.Now()).Sub(c.store.data[item].lastUpdate) + + c.store.mutex.RUnlock() + + if diff <= c.duration { + + l.Trace.Printf("[CACHE] Object [ %v ] cache hasn't expired yet.\n", item) + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return object.value, nil + + } + + l.Warning.Printf("[CACHE] Object [ %v ] cache has expired. Starting the upgrade.\n", item) + + if e := c.fetch(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while fetching the updated data for the object [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects refreshed"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] updated retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects refreshed"}).Inc() + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return o, nil + +} diff --git a/extensions/lexis/server/config.go b/extensions/lexis/server/config.go new file mode 100644 index 0000000..c94206b --- /dev/null +++ b/extensions/lexis/server/config.go @@ -0,0 +1,258 @@ +package main + +import ( + "strings" + + "github.com/segmentio/encoding/json" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + Credit creditConfig + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + OpenStack openStackConfig + Plans planConfig + Prometheus prometheusConfig +} + +type creditConfig struct { + Usage bool +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type openStackConfig struct { + Domain string + Filters []string + Keystone string + Password string + Project string + Regions []string + User string +} + +type planConfig struct { + Default string +} + +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + cfgCopy.OpenStack.Password = masked(c.OpenStack.Password, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + Credit: creditConfig{ + Usage: viper.GetBool("credit.usageinsteadofcost"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("portaldb.cacheretention"), + DbName: viper.GetString("portaldb.dbname"), + Host: viper.GetString("portaldb.host"), + Password: viper.GetString("portaldb.password"), + Port: viper.GetInt("portaldb.port"), + SSLMode: viper.GetString("portaldb.sslmode"), + Username: viper.GetString("portaldb.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + OpenStack: openStackConfig{ + Domain: viper.GetString("openstack.domain"), + Filters: viper.GetStringSlice("openstack.filters"), + Keystone: viper.GetString("openstack.keystone"), + Password: viper.GetString("openstack.password"), + Project: viper.GetString("openstack.project"), + Regions: viper.GetStringSlice("openstack.region"), + User: viper.GetString("openstack.user"), + }, + + Plans: planConfig{ + Default: viper.GetString("Plans.default"), + }, + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/extensions/lexis/server/dbManager/dbManager.go b/extensions/lexis/server/dbManager/dbManager.go new file mode 100644 index 0000000..2fb67c7 --- /dev/null +++ b/extensions/lexis/server/dbManager/dbManager.go @@ -0,0 +1,524 @@ +package dbManager + +import ( + "context" + "math" + "net/http" + "reflect" + "strings" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/segmentio/encoding/json" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/cacheManager" + csClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client" + csAccount "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client/account_management" + csCredit "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client/credit_management" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + cusReseller "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/reseller_management" + cusModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + udrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +// Report status code vars +const ( + scaler = 1e4 + StatusDuplicated = iota + StatusFail + StatusMissing + StatusOK +) + +type Config struct { + CustomerDB cusClient.Config + CreditSystem csClient.Config + PlanManager pmClient.Config + UDR udrClient.Config + OpenStack OpenStackConfig +} + +// OpenStackConfig is the struck to hold the configuration parameters needed +// for quering the flavors active in OpenStack. +type OpenStackConfig struct { + Domain string + Filters []string + Keystone string + Password string + Project string + Regions []string + Username string +} + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// Parameters: +// - Cache: CacheManager pointer for the cache mechanism. +// - connStr: strings with the connection information to the database +// - Db: a gorm.DB pointer to the db to invoke all the db methods +type DbParameter struct { + Cache *cacheManager.CacheManager + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec + Configs Config +} + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization +// Returns: +// - DbParameter: struct to interact with dbManager functionalities +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + panic(err) + + } + + //l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + //dp.Db.AutoMigrate(tables...) + + //l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + //dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NewScope(&models.TABLE).TableName() + "', 'TIMESCALE-ROW-INDEX');") + + return &dp + +} + +// getCusClient job is to initialize a customerDB client to be able to connect +// to the customerDB service. +// Parameters: +// - http.Request parameter to extract the keycloak bearer token if exists. +// Returns: +// - CustomerDB client struct for connecting to the custoimerDB service. +func (m *DbParameter) getCusClient(param *http.Request) *cusClient.CustomerDatabaseManagement { + + config := m.Configs.CustomerDB + + if len(param.Header.Get("Authorization")) > 0 { + + token := strings.Fields(param.Header.Get("Authorization"))[1] + + config.AuthInfo = httptransport.BearerToken(token) + + } + + r := cusClient.New(config) + + return r + +} + +// getCSClient job is to initialize a credit system client to be able to connect +// to the credit system service. +// Parameters: +// - http.Request parameter to extract the keycloak bearer token if exists. +// Returns: +// - CreditSystem client struct for connecting to the creditSystem service. +func (m *DbParameter) getCSClient(param *http.Request) *csClient.CreditManagerManagementAPI { + + config := m.Configs.CreditSystem + + if len(param.Header.Get("Authorization")) > 0 { + + token := strings.Fields(param.Header.Get("Authorization"))[1] + + config.AuthInfo = httptransport.BearerToken(token) + + } + + r := csClient.New(config) + + return r + +} + +// getFloat job is to check the type of the interface and properly cast its +// getFloat job is to check the type of the interface and properly cast its +// value into a float64. +// Parameters: +// - i: interface that should contain a float number. +// Returns: +// - f: a float64 with the value contained in the interface provided. +func (m *DbParameter) getFloat(i interface{}) (f float64) { + + var e error + + if i == nil { + + f = float64(0) + + return + + } + + if v := reflect.ValueOf(i); v.Kind() == reflect.Float64 { + + f = i.(float64) + + } else { + + f, e = i.(json.Number).Float64() + + if e != nil { + + l.Trace.Printf("[DB] GetFloat failed to convert [ %v ]. Error: %v\n", i, e) + + } + + } + + return + +} + +// getNiceFloat job is to turn the ugly float64 provided into a "nice looking" +// one according to the scale set, so we move from a floating coma number into +// a fixed coma number. +// Parameters: +// - i: the ugly floating coma number. +// Returns: +// - o: the "nice looking" fixed coma float. +func (m *DbParameter) getNiceFloat(i float64) (o float64) { + + min := float64(float64(1) / float64(scaler)) + + if diff := math.Abs(i - min); diff < min { + + o = float64(0) + + } else { + + o = float64(math.Round(i*scaler) / scaler) + + } + + return + +} + +// getNiceFloat job is to turn the ugly float64 provided into a "nice looking" +// one according to the scale set, so we move from a floating coma number into +// a fixed coma number. +// Parameters: +// - i: the ugly floating coma number. +// Returns: +// - o: the "nice looking" fixed coma float. +func (m *DbParameter) getNiceFloatAVG(i float64) (o float64) { + + scaler := 1e2 + + min := float64(float64(1) / float64(scaler)) + + if diff := math.Abs(i - min); diff < min { + + o = float64(0) + + } else { + + o = float64(math.Round(i*scaler) / scaler) + + } + + return + +} + +func (m *DbParameter) SyncHierarchy(ctx context.Context, param *http.Request) (state int, e error) { + + var resellers []*cusModels.Reseller + var orgs []*models.Organization + billingPeriod := "monthly" + billingCurrency := "EUR" + billingPlan := "1" + + creditsProjects := make(map[string]float64) + + // get all the organizations + // - create a reseller entity + if e = m.Db.Find(&orgs).Error; e != nil { + + l.Warning.Printf("[SYNC] Error retrieving the list of orgs in the system. Error: %v\n", e) + + state = StatusFail + + return + + } + + for _, org := range orgs { + + var customers []*cusModels.Customer + var prjs []*models.Project + + active := org.OrganizationStatus == "APPROVED" + + reseller := cusModels.Reseller{ + Address: org.RegisteredAddress1 + "; " + org.RegisteredAddress2 + "; " + org.RegisteredAddress3, + Billable: &active, + BillContact: org.CreatedBy.String(), + BillCurrency: &billingCurrency, + BillPeriod: &billingPeriod, + ContractStart: (strfmt.Date)(org.CreationDate), + Discount: float64(0), + EmailTo: org.OrganizationEmailAddress, + IsActive: &active, + Name: org.FormalName, + PlanID: billingPlan, + ResellerID: org.ID.String(), + } + + if e = m.Db.Where(models.Project{LinkedOrganization: org.ID}).Find(&prjs).Error; e != nil { + + l.Warning.Printf("[SYNC] Error retrieving the list of prjs for Organization [ %v ] in the system. Error: %v\n", org.ID, e) + + continue + + } + + // for each, get all the project + // - create a customer entity + for _, prj := range prjs { + + var products []*cusModels.Product + var hpcres []*models.HPCResource + + prjActive := prj.ProjectStatus == "ACTIVE" + customer := cusModels.Customer{ + Billable: &prjActive, + BillContact: prj.ProjectCreatedBy.String(), + BillCurrency: &billingCurrency, + BillPeriod: &billingPeriod, + ContractEnd: (strfmt.Date)(prj.ProjectTerminationDate), + ContractStart: (strfmt.Date)(prj.ProjectStartDate), + CustomerID: prj.ProjectID.String(), + Discount: float64(0), + EmailTo: prj.ProjectContactEmail, + IsActive: &prjActive, + Name: prj.ProjectName, + PlanID: billingPlan, + ResellerID: org.ID.String(), + } + + creditsProjects[prj.ProjectID.String()] = float64(*prj.NormCoreHours) + + if e = m.Db.Where(models.HPCResource{AssociatedLEXISProject: prj.ProjectID}).Find(&hpcres).Error; e != nil { + + l.Warning.Printf("[SYNC] Error retrieving the list of HPCResources for Project [ %v ] in the system. Error: %v\n", prj.ProjectID, e) + + continue + + } + + // for each get all the HPCRes + // - create a product entity + for _, hpc := range hpcres { + + if hpc.ApprovalStatus != "ACCEPTED" { + + l.Info.Printf("[SYNC] HPCResource [ %v ] for Project [ %v ] not accepted yet, skipping...\n", hpc.HPCResourceID, prj.ProjectID) + + continue + + } + + id := hpc.OpenStackProjectID + + if id == "" { + + id = hpc.AssociatedHPCProject + + } + + product := cusModels.Product{ + CustomerID: prj.ProjectID.String(), + Discount: float64(0), + Name: hpc.HPCProvider + " " + hpc.AssociatedHPCProject, + ProductID: id, + Type: hpc.HPCProvider + "-" + hpc.ResourceType, + } + + products = append(products, &product) + + } + customer.Products = products + + customers = append(customers, &customer) + + } + + reseller.Customers = customers + + resellers = append(resellers, &reseller) + + } + + // For each, first try to create, + // if fail, then to update + // if fail, ignore and continue + customerDB := m.getCusClient(param) + creditSystem := m.getCSClient(param) + + creditAccounts := make(map[string]bool) + + csParams := csAccount.NewListAccountsParams() + r, err := creditSystem.AccountManagement.ListAccounts(ctx, csParams) + + if err != nil { + + l.Warning.Printf("[SYNC] Error retrieving the list of Credit accounts in the system. Error: %v\n", e) + + } else { + + acs := r.Payload + + for i := range acs { + + creditAccounts[acs[i].AccountID] = acs[i].Enabled + + } + + } + + for i := range resellers { + + params := cusReseller.NewAddResellerParams().WithReseller(resellers[i]) + + _, _, err := customerDB.ResellerManagement.AddReseller(ctx, params) + + if err != nil { + + l.Warning.Printf("[SYNC] Error while adding the data for reseller. Trying with an update... Error: %v", err) + + uParams := cusReseller.NewUpdateResellerParams().WithReseller(resellers[i]).WithID(resellers[i].ResellerID) + + _, _, err := customerDB.ResellerManagement.UpdateReseller(ctx, uParams) + + if err != nil { + + l.Warning.Printf("[SYNC] Error while updating the data for reseller. Error: %v", err) + + } + + } + + // Credit: + // create account + // if project active -> credit ac to enable + // if credit ac previously was diable then add normCorehours as credit amount + for _, customer := range resellers[i].Customers { + + active, exists := creditAccounts[customer.CustomerID] + + if exists && active { + + continue + + } + + if !exists { + + csParams := csAccount.NewCreateAccountParams().WithID(customer.CustomerID) + _, err := creditSystem.AccountManagement.CreateAccount(ctx, csParams) + + if err != nil { + + l.Warning.Printf("[SYNC] Error creating the Credit accounts in the system for project [ %v ]. Error: %v\n", customer.CustomerID, err) + + continue + + } + + exists = true + active = false + + } + + if *customer.Billable { + + if exists && !active { + + csParams := csAccount.NewEnableAccountParams().WithID(customer.CustomerID) + _, err := creditSystem.AccountManagement.EnableAccount(ctx, csParams) + + if err != nil { + + l.Warning.Printf("[SYNC] Error enabling the Credit accounts in the system for project [ %v ]. Error: %v\n", customer.CustomerID, err) + + continue + + } + + active = true + + } + + } else { + + if exists && active { + + csParams := csAccount.NewDisableAccountParams().WithID(customer.CustomerID) + _, err := creditSystem.AccountManagement.DisableAccount(ctx, csParams) + + if err != nil { + + l.Warning.Printf("[SYNC] Error disabling the Credit accounts in the system for project [ %v ]. Error: %v\n", customer.CustomerID, err) + + continue + + } + + active = false + + } + + } + + if hours, hasHours := creditsProjects[customer.CustomerID]; exists && active && hasHours { + + csParams := csCredit.NewIncreaseCreditParams().WithID(customer.CustomerID).WithAmount(hours).WithMedium("credit") + _, err := creditSystem.CreditManagement.IncreaseCredit(ctx, csParams) + + if err != nil { + + l.Warning.Printf("[SYNC] Error setting the Credit for the account for project [ %v ] in the system. Error: %v\n", customer.CustomerID, err) + + continue + + } + + } + + } + + } + + return + +} diff --git a/extensions/lexis/server/kafka.go b/extensions/lexis/server/kafka.go new file mode 100644 index 0000000..be15dbb --- /dev/null +++ b/extensions/lexis/server/kafka.go @@ -0,0 +1,298 @@ +package main + +import ( + "context" + "crypto/tls" + "reflect" + "strconv" + "time" + + "github.com/segmentio/encoding/json" + + "github.com/prometheus/client_golang/prometheus" + kafka "github.com/segmentio/kafka-go" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaFunction func(*dbManager.DbParameter, interface{}) error + +type kafkaHandlerConf struct { + in []kafkaPackage + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + model interface{} + function kafkaFunction + channel chan interface{} + saveDB bool +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(db *dbManager.DbParameter, monit *statusManager.StatusManager, kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.in != nil { + + monit.InitEndpoint("kafka-receiver") + + for _, p := range kH.in { + + go kafkaReceiver(db, monit, p.topic, p.partition, p.model, p.function, p.saveDB) + + } + } + + if kH.out != nil { + + monit.InitEndpoint("kafka-sender") + + for _, p := range kH.out { + + go kafkaSender(db, monit, p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaReceiver is the abstracted interface used to receive JSON data from kafka. +// The functions assumes that by default anything that comes from the kafka topic +// and validates against a specific data model has to be added to the db. +// Besides that it has the option to call an external function to interact with +// the data before putting it in the db. +// Parameters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - m: model to validate data against. +// - f: optional external function for more functionality. +// - saveDB: bool to control is the received data needs to be saved in the db. +func kafkaReceiver(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, m interface{}, f kafkaFunction, saveDB bool) { + + l.Trace.Printf("[KAFKA] Initializing kafka receiver for topic: %v.\n", t) + + conf := kafka.ReaderConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Partition: p, + MinBytes: cfg.Kafka.MinBytes, + MaxBytes: cfg.Kafka.MaxBytes, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + r := kafka.NewReader(conf) + defer r.Close() + + if e := r.SetOffset(cfg.Kafka.Offset); e != nil { + + l.Warning.Printf("[KAFKA] There was a problem when setting the offset, stopping the kafka handler NOW. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream offset"}).Inc() + + return + + } + + for { + + callTime := time.Now() + monit.APIHit("kafka-receiver", callTime) + + rm, e := r.ReadMessage(context.Background()) + + if e != nil { + + l.Warning.Printf("[KAFKA] Error detected in the kafka stream. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream"}).Inc() + + monit.APIHitDone("kafka-receiver", callTime) + + continue + + } + + o := reflect.New(reflect.TypeOf(m)).Interface() + + if e := json.Unmarshal(rm.Value, &o); e == nil { + + l.Info.Printf("[KAFKA] Relevant information detected in the stream: Topic: %v, partition: %v.\n", t, p) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object received"}).Inc() + + if f != nil { + + l.Info.Printf("[KAFKA] Function for specialized work detected. Starting its processing.\n") + + if err := f(db, o); err != nil { + + l.Warning.Printf("[KAFKA] There was a problem processing the model's specific function. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: linked function"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: linked function"}).Inc() + + } + + } + + if saveDB { + + l.Info.Printf("[KAFKA] Saving procesed record in the database.\n") + + if err := db.Db.Create(o).Error; err != nil { + + l.Warning.Printf("[KAFKA] There was a problem adding the record into the database. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: db saving"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object db saved"}).Inc() + + } + + } + + } else { + + l.Warning.Printf("[KAFKA] The information in the stream does not fit the expected model, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream-rubish"}).Inc() + + } + + monit.APIHitDone("kafka-receiver", callTime) + + } + +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + l.Info.Printf("[KAFKA] The channel has problems or has been closed.\n") + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: channel"}).Inc() + + break + + } + + m, e := json.Marshal(&v) + + if e == nil { + + callTime := time.Now() + monit.APIHit("kafka-sender", callTime) + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: stream"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "OK: object sent"}).Inc() + + } + + monit.APIHitDone("kafka-sender", callTime) + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: JSON Marshalling"}).Inc() + + } + + } + +} diff --git a/extensions/lexis/server/main.go b/extensions/lexis/server/main.go new file mode 100644 index 0000000..8ec44fd --- /dev/null +++ b/extensions/lexis/server/main.go @@ -0,0 +1,177 @@ +package main + +import ( + "crypto/tls" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/segmentio/encoding/json" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/extensions/lexis/server/metrics.go b/extensions/lexis/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/extensions/lexis/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/extensions/lexis/server/security.go b/extensions/lexis/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/extensions/lexis/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/extensions/lexis/server/service.go b/extensions/lexis/server/service.go new file mode 100644 index 0000000..fdaa849 --- /dev/null +++ b/extensions/lexis/server/service.go @@ -0,0 +1,185 @@ +package main + +import ( + "net/http" + "net/url" + "strings" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/statusManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/syncManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/triggerManager" + csClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + udrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,1,n have to be customized + db := dbStart() + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + // cache linked to the dbParameter + db.Cache = cacheStart(db.Metrics["cache"]) + + // In case of needed, here is where kafka support is started + // The functions needs to be customized accordingly to the needs of the service + // And the parts of the service that might need to send messages need to get + // the channel + // _ = kafkaStart(db, mon) + + //bp := getBasePath() + + db.Configs.CreditSystem = csClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["creditsystem"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + db.Configs.CustomerDB = cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + db.Configs.PlanManager = pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + db.Configs.UDR = udrClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["udr"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + db.Configs.OpenStack = dbManager.OpenStackConfig{ + Domain: cfg.OpenStack.Domain, + Filters: cfg.OpenStack.Filters, + Keystone: cfg.OpenStack.Keystone, + Password: cfg.OpenStack.Password, + Project: cfg.OpenStack.Project, + Regions: cfg.OpenStack.Regions, + Username: cfg.OpenStack.User, + } + + // Parts of the service HERE + syncer := syncManager.New(db, mon) + trigger := triggerManager.New(db, mon) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + SyncManagementAPI: syncer, + TriggerManagementAPI: trigger, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Parameters: +// - db: DbPAramenter reference for interaction with the db. +// - mon: statusManager parameter reference to interact with the statusManager +// subsystem +// Returns: +// - ch: a interface{} channel to be able to send thing through the kafka topic generated. +func kafkaStart(db *dbManager.DbParameter, mon *statusManager.StatusManager) (ch chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + f := func(db *dbManager.DbParameter, model interface{}) (e error) { + + ////if e = db.ProcessCDR(*model.(*cdrModels.CReport), ""); e != nil { + + //// l.Warning.Printf("[KAFKA] There was an error while apliying the linked function. Error: %v\n", e) + + ////} else { + + //// l.Trace.Printf("[KAFKA] Aplication of the linked function done succesfully.\n") + + ////} + + return + + } + + ch = make(chan interface{}) + + handler := kafkaHandlerConf{ + in: []kafkaPackage{ + { + topic: cfg.Kafka.TopicsIn[0], + model: nil, + function: f, + saveDB: false, + }, + }, + } + + kafkaHandler(db, mon, handler) + + return + +} diff --git a/extensions/lexis/server/statusManager/statusManager.go b/extensions/lexis/server/statusManager/statusManager.go new file mode 100644 index 0000000..4810426 --- /dev/null +++ b/extensions/lexis/server/statusManager/statusManager.go @@ -0,0 +1,314 @@ +package statusManager + +import ( + "context" + "fmt" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + avgTime[key] = t.UnixNano() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + if previous, exists := avgTime[key]; exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + delete(avgTime, key) + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/extensions/lexis/server/syncManager/flavors.go b/extensions/lexis/server/syncManager/flavors.go new file mode 100644 index 0000000..48b6f18 --- /dev/null +++ b/extensions/lexis/server/syncManager/flavors.go @@ -0,0 +1,248 @@ +package syncManager + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/gophercloud/gophercloud" + "github.com/gophercloud/gophercloud/openstack" + "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors" + "gitlab.com/cyclops-utilities/datamodels" + pmBundle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/bundle_management" + pmModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + l "gitlab.com/cyclops-utilities/logging" +) + +func (m *SyncManager) updateBundles(param *http.Request) (state int, err error) { + + l.Trace.Printf("[LoaderManager] UpdateBundles endpoint invoked.\n") + + var opts gophercloud.AuthOptions + var bundles []*pmModels.SkuBundle + + opts = gophercloud.AuthOptions{ + IdentityEndpoint: m.db.Configs.OpenStack.Keystone, + Username: m.db.Configs.OpenStack.Username, + Password: m.db.Configs.OpenStack.Password, + DomainName: m.db.Configs.OpenStack.Domain, + } + + if len(m.db.Configs.OpenStack.Project) > 0 { + + opts.TenantName = m.db.Configs.OpenStack.Project + + } + + provider, e := openstack.AuthenticatedClient(opts) + + if e != nil { + + l.Error.Printf("[SyncManager] Authentication failed. Error: %v", e) + + state = statusFail + err = e + + return + + } + + pmClient := m.getPMClient(param) + ctx := context.Background() + + for _, region := range m.db.Configs.OpenStack.Regions { + + l.Info.Printf("[SyncManager] Processing OS region: %s\n", region) + + client, e := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{ + Region: region, + }) + + if e != nil { + + l.Warning.Printf("[SyncManager] There was a problem creating compute collector client. Error: %v", e) + + state = statusFail + err = e + + return + + } + + listOpts := flavors.ListOpts{ + AccessType: flavors.AllAccess, + } + + allPages, e := flavors.ListDetail(client, listOpts).AllPages() + + if e != nil { + + l.Warning.Printf("[SyncManager] There was a problem while getting flavor list. Error: %v", e) + + state = statusFail + err = e + + return + + } + + allFlavors, e := flavors.ExtractFlavors(allPages) + + if e != nil { + + l.Warning.Printf("[SyncManager] Could not extract flavors. Error: %v", e) + + state = statusFail + err = e + + return + + } + + flavorLoop: + + for _, flavor := range allFlavors { + + name := strings.ToLower(flavor.Name) + + for _, filter := range m.db.Configs.OpenStack.Filters { + + if strings.Contains(flavor.Name, filter) { + + continue flavorLoop + + } + + } + + l.Trace.Printf("[SyncManager] Located flavor: VCPUs: %2d, Disk (GB): %3d, RAM (MB): %5d, Name: %15s, ID:%s\n", flavor.VCPUs, flavor.Disk, flavor.RAM, flavor.Name, flavor.ID) + + //here insert or update flavor details in the db + var bundle pmModels.SkuBundle + + bundle.ID = flavor.ID + bundle.Name = &flavor.Name + bundle.SkuPrices = make(datamodels.JSONdb) + + bundle.SkuPrices["vcpu"] = int64(flavor.VCPUs) + bundle.SkuPrices["ram"] = float64(float64(flavor.RAM) / float64(1024)) + + fmt.Printf("RAM: %v\n", bundle.SkuPrices["ram"]) + + if strings.Contains(name, "windows") { + + bundle.SkuPrices["license"] = int64(flavor.VCPUs) + + } + + if strings.HasPrefix(name, "g1") { + + l.Trace.Printf("[SyncManager] Found a GPU flavor: %s, proceeding to parse next.\n", name) + + var temp string + + if strings.Contains(name, "t4") { + + temp = "t4" + + } + + if strings.Contains(name, "p100") { + + temp = "p100" + + } + + if strings.Contains(name, "titanxp") { + + temp = "titanxp" + + } + + typeCut := strings.Split(name, temp) + coresCut := strings.Split(typeCut[0], "-") + + var gpucount int64 + + if coresCut[len(coresCut)-1] == "" { + + gpucount = int64(1) + + } else { + + n, e := strconv.ParseInt(coresCut[len(coresCut)-1], 10, 64) + + if e != nil { + + l.Warning.Printf("[SyncManager] Non numeric count detected in gpu flavor name %s\n", name) + + } else { + + gpucount = n + + } + + } + + bundle.SkuPrices[temp] = int64(gpucount) + + } + + if strings.Contains(name, "ssd") { + + bundle.SkuPrices["rootdisk_ssd"] = float64(flavor.Disk) + bundle.SkuPrices["ephemeraldisk_ssd"] = float64(flavor.Ephemeral) + + } else { + + bundle.SkuPrices["rootdisk"] = float64(flavor.Disk) + bundle.SkuPrices["ephemeraldisk"] = float64(flavor.Ephemeral) + + } + + params := pmBundle.NewCreateSkuBundleParams().WithBundle(&bundle) + + _, e = pmClient.BundleManagement.CreateSkuBundle(ctx, params) + + if e != nil { + + uparams := pmBundle.NewUpdateSkuBundleParams().WithID(bundle.ID).WithBundle(&bundle) + + _, e := pmClient.BundleManagement.UpdateSkuBundle(ctx, uparams) + + if e != nil { + + err = e + state = statusFail + + } else { + + state = statusOK + + } + + } + + bundles = append(bundles, &bundle) + + } + + } + + state = statusOK + + if len(bundles) < 1 { + + state = statusFail + + } else if e != nil { + + state = statusMissing + + } + + return + +} diff --git a/extensions/lexis/server/syncManager/syncManager.go b/extensions/lexis/server/syncManager/syncManager.go new file mode 100644 index 0000000..60e2383 --- /dev/null +++ b/extensions/lexis/server/syncManager/syncManager.go @@ -0,0 +1,202 @@ +package syncManager + +import ( + "context" + "fmt" + "net/http" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/sync_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/statusManager" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// SyncManager is the struct defined to group and contain all the methods +// that interact with the sync subsystem. +type SyncManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +var returnValue models.ErrorResponse + +// New is the function to create the struct SyncManager. +// Returns: +// - SyncManager: *struct to interact with SyncManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *SyncManager { + + l.Trace.Printf("[SyncManager] Generating new SyncManager.\n") + + monit.InitEndpoint("sync") + + // Default return string in case something weird happens. + // It usually means that something went wrong in the dbManager. + s := "Something unexpected happened, check with the administrator." + + returnValue = models.ErrorResponse{ + ErrorString: &s, + } + + return &SyncManager{ + db: db, + monit: monit, + } + +} + +// getCusClient job is to initialize a customerDB client to be able to connect +// to the customerDB service. +// Parameters: +// - http.Request parameter to extract the keycloak bearer token if exists. +// Returns: +// - CustomerDB client struct for connecting to the custoimerDB service. +func (m *SyncManager) getCusClient(param *http.Request) *cusClient.CustomerDatabaseManagement { + + config := m.db.Configs.CustomerDB + + if len(param.Header.Get("Authorization")) > 0 { + + token := strings.Fields(param.Header.Get("Authorization"))[1] + + config.AuthInfo = httptransport.BearerToken(token) + + } + + r := cusClient.New(config) + + return r + +} + +// getPMClient job is to initialize a planManager client to be able to connect +// to the planManager service. +// Parameters: +// - http.Request parameter to extract the keycloak bearer token if exists. +// Returns: +// - PlanManager client struct for connecting to the PlanManager service. +func (m *SyncManager) getPMClient(param *http.Request) *pmClient.PlanManagerManagementAPI { + + config := m.db.Configs.PlanManager + + if len(param.Header.Get("Authorization")) > 0 { + + token := strings.Fields(param.Header.Get("Authorization"))[1] + + config.AuthInfo = httptransport.BearerToken(token) + + } + + r := pmClient.New(config) + + return r + +} + +// SyncHierarchy (Swagger func) is the function behind the (GET) endpoint +// /load/customers +// Its job is to process the data from SWITCH coscenters endpoint and load +// them into Cyclops. +func (m *SyncManager) SyncHierarchy(ctx context.Context, params sync_management.SyncHierarchyParams) middleware.Responder { + + l.Trace.Printf("[SyncManager] Starting the loading of customers.\n") + + callTime := time.Now() + m.monit.APIHit("sync", callTime) + + state, e := m.db.SyncHierarchy(ctx, params.HTTPRequest) + + switch state { + + case statusOK: + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("sync", callTime) + + return sync_management.NewSyncHierarchyOK() + + case statusFail: + + err := fmt.Sprintf("Something went wrong with the Hierarchy processing. Error: %v", e) + + returnValueError := models.ErrorResponse{ + ErrorString: &err, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("sync", callTime) + + return sync_management.NewSyncHierarchyInternalServerError().WithPayload(&returnValueError) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusAccepted), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("sync", callTime) + + return sync_management.NewSyncHierarchyAccepted() + +} + +// SyncFlavors (Swagger func) is the function behind the (GET) endpoint +// /load/flavors +// Its job is to process the data from OppenStack flavors in SWITCH and load +// them into Cyclops. +func (m *SyncManager) SyncFlavors(ctx context.Context, params sync_management.SyncFlavorsParams) middleware.Responder { + + l.Trace.Printf("[SyncManager] Starting the loading of flavors.\n") + + callTime := time.Now() + m.monit.APIHit("sync", callTime) + + state, e := m.updateBundles(params.HTTPRequest) + + switch state { + + case statusOK: + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("sync", callTime) + + return sync_management.NewSyncFlavorsOK() + + case statusFail: + + err := fmt.Sprintf("Something went wrong with the Flavors processing. Error: %v", e) + + returnValueError := models.ErrorResponse{ + ErrorString: &err, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("sync", callTime) + + return sync_management.NewSyncFlavorsInternalServerError().WithPayload(&returnValueError) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusAccepted), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("sync", callTime) + + return sync_management.NewSyncFlavorsAccepted() + +} diff --git a/extensions/lexis/server/triggerManager/triggerManager.go b/extensions/lexis/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..b4f3026 --- /dev/null +++ b/extensions/lexis/server/triggerManager/triggerManager.go @@ -0,0 +1,133 @@ +package triggerManager + +import ( + "context" + "net/http" + "strings" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/extensions/lexis/server/statusManager" + udrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client" + udrTrigger "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client/trigger_management" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + scaler = 1e4 + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +type TriggerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +var returnValue models.ErrorResponse + +// New is the function to create the struct TriggerManager. +// Returns: +// - TriggerManager: *struct to interact with LoaderManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *TriggerManager { + + l.Trace.Printf("[TriggerManager] Generating new triggerManager.\n") + + monit.InitEndpoint("trigger") + + // Default return string in case something weird happens. + // It usually means that something went wrong in the dbManager. + s := "Something unexpected happened, check with the administrator." + + returnValue = models.ErrorResponse{ + ErrorString: &s, + } + + return &TriggerManager{ + db: db, + monit: monit, + } + +} + +// getToken job is to retrieve the keycloak bearer token from the Http.Request. +// Parameters: +// - http.Request parameter to extract the keycloak bearer token if exists. +// Returns: +// - string with the optional Keycloak bearer token. +func (m *TriggerManager) getToken(param *http.Request) (token string) { + + if len(param.Header.Get("Authorization")) > 0 { + + token = strings.Fields(param.Header.Get("Authorization"))[1] + + } + + return + +} + +func (m *TriggerManager) UDRRedo(ctx context.Context, params trigger_management.UDRRedoParams) middleware.Responder { + + l.Trace.Printf("[Trigger] Generate Reports endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + go func() { + + client := udrClient.New(m.db.Configs.UDR) + + increment, _ := time.ParseDuration(*params.Interval) + + f := (time.Time)(*params.From) + end := (time.Time)(*params.To) + + from := strfmt.DateTime(f) + f = f.Add(increment) + to := strfmt.DateTime(f) + + for end.Sub(f.Add(-increment)) >= increment { + + l.Trace.Printf("UDR Compact requested for %v to %v", from, to) + + params := udrTrigger.NewExecCompactationParams().WithFrom(&from).WithTo(&to) + ctx = context.Background() + + _, e := client.TriggerManagement.ExecCompactation(ctx, params) + + if e != nil { + + l.Warning.Printf("There was a problem while compacting UDR from [ %v ], to [ %v ]. Error: %v", from, to, e) + + } else { + + l.Trace.Printf("UDR Compact completed for %v to %v", from, to) + + } + + from = to + f = f.Add(increment) + to = strfmt.DateTime(f) + + time.Sleep(1 * time.Second) + + } + + m.monit.APIHitDone("trigger", callTime) + + }() + + returnValue := models.ItemCreatedResponse{ + Message: "Report generation started", + } + + return trigger_management.NewUDRRedoOK().WithPayload(&returnValue) + +} diff --git a/extensions/lexis/swagger.yaml b/extensions/lexis/swagger.yaml new file mode 100644 index 0000000..1847a4e --- /dev/null +++ b/extensions/lexis/swagger.yaml @@ -0,0 +1,389 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v0.1" +info: + description: An API which supports creation, deletion, listing etc of SERVICE + version: "0.1.0" + title: LEXIS Extension Management API + contact: + email: diego@cyclops-labs.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: syncManagement + description: Actions relating to the syncing of data from LEXIS into cyclops services. + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - kafka-receiver + - kafka-sender + - status + - trigger + - metrics + - sync + required: true + description: Id of the endpoint to be checked + + /trigger/udrsredo: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Redo of UDRs from the specific dates and with the specifc interval + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: UDRRedo + responses: + '200': + description: Generation task executed successfully. + schema: + $ref: "#/definitions/ItemCreatedResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: from + in: query + description: Datetime from which to regenerate the udrs + type: string + format: datetime + - name: to + in: query + description: Datetime until which to regenerate the udrs + type: string + format: datetime + - name: interval + in: query + description: Interval to do increments + type: string + + /sync/hierarchy: + get: + tags: + - syncManagement + produces: + - application/json + summary: syncs all the organizations, projects, resources hierarchy from LEXIS + operationId: syncHierarchy + responses: + '200': + description: The load of data was completely successfully + '202': + description: Operation done but there might have been some fails when adding part of the data + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + + /sync/flavors: + get: + tags: + - syncManagement + produces: + - application/json + summary: Sync the OpenStack's flavors data in the system + operationId: syncFlavors + responses: + '200': + description: The load of data was completely successfully + '202': + description: Operation done but there might have been some fails when adding part of the data + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + ItemCreatedResponse: + properties: + Message: + type: string + Metadata: + type: object + x-go-type: + import: + package: "gitlab.com/cyclops-utilities/datamodels" + type: JSONdb + StringArray: + x-go-type: + import: + package: "github.com/lib/pq" + type: StringArray + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + + #User-Org: + Organization: + type: object + properties: + ID: + type: string + format: uuid + x-go-custom-tag: gorm:"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + FormalName: + type: string + x-go-custom-tag: gorm:"column:formalname" + RegisteredAddress1: + type: string + x-go-custom-tag: gorm:"column:registeredaddress1" + RegisteredAddress2: + type: string + x-go-custom-tag: gorm:"column:registeredaddress2" + RegisteredAddress3: + type: string + x-go-custom-tag: gorm:"column:registeredaddress3" + RegisteredCountry: + type: string + format: country + x-go-custom-tag: gorm:"column:registeredcountry" + CreationDate: + type: string + format: date-time + x-go-custom-tag: gorm:"column:registrationdatetime;type:timestamptz" + CreatedBy: + # userid who created this organization + type: string + format: uuid + x-go-custom-tag: gorm:"column:createdby;type:uuid" + Website: + type: string + format: url + OrganizationEmailAddress: + type: string + format: email + x-go-custom-tag: gorm:"column:organizationemailaddress" + PrimaryTelephoneNumber: + type: string + format: telephone-number + x-go-custom-tag: gorm:"column:primarytelephonenumber" + VATRegistrationNumber: + type: string + x-go-custom-tag: gorm:"column:vatregistrationnumber" + OrganizationStatus: + type: string + enum: + - PENDING_APPROVAL + - APPROVED + - DISABLED + - TERMINATED + x-go-custom-tag: gorm:"column:organizationstatus" + + Project: + type: object + properties: + ProjectID: + type: string + format: uuid + x-go-custom-tag: gorm:"column:projectid;type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + ProjectName: + type: string + x-go-custom-tag: gorm:"column:projectname" + ProjectShortName: + type: string + x-go-custom-tag: gorm:"column:projectshortname;unique" + ProjectDescription: + type: string + x-go-custom-tag: gorm:"column:projectdescription" + ProjectCreationTime: + type: string + format: date-time + x-go-custom-tag: gorm:"column:projectcreationtime;type:timestamptz;default:now()" + ProjectCreatedBy: + type: string + format: uuid + x-go-custom-tag: gorm:"column:projectcreatedby;type:uuid" + LinkedOrganization: + type: string + format: uuid + x-go-custom-tag: gorm:"column:linkedorganization;type:uuid" + AllowedOrganizations: + $ref: '#/definitions/StringArray' + x-go-custom-tag: gorm:"column:allowedorganizations;type:text[]" + ProjectStatus: + type: string + enum: + - PENDING + - ACTIVE + - DISABLED + - TERMINATED + x-go-custom-tag: gorm:"column:projectstatus" + ProjectContactPerson: + type: string + format: uuid + x-go-custom-tag: gorm:"column:projectcontactperson;type:uuid" + ProjectStartDate: + type: string + format: date-time + x-go-custom-tag: gorm:"column:projectstartdate;type:timestamptz" + ProjectTerminationDate: + type: string + format: date-time + x-go-custom-tag: gorm:"column:projectterminationdate;type:timestamptz" + ProjectMaxPrice: + type: number + format: double + default: 0.0 + x-nullable: true + x-go-custom-tag: gorm:"column:projectmaxprice;type:float8;default:0.0" + NormCoreHours: + type: integer + default: 0 + x-nullable: true + x-go-custom-tag: gorm:"column:normcorehours;default:0" + ProjectContactEmail: + type: string + format: email + x-go-custom-tag: gorm:"column:projectcontactemail" + ProjectDomain: + type: string + x-go-custom-tag: gorm:"column:projectdomain" + + HPCResource: + type: object + properties: + HPCResourceID: + type: string + x-go-custom-tag: gorm:"column:hpcresourceid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + AssociatedHPCProject: + type: string + x-go-custom-tag: gorm:"column:associatedhpcproject" + AssociatedLEXISProject: + type: string + format: uuid + x-go-custom-tag: gorm:"column:associatedlexisproject;type:uuid" + ApprovalStatus: + type: string + enum: + - ACCEPTED + - REJECTED + - PENDING + x-go-custom-tag: gorm:"column:approvalstatus" + CloudNetworkName: + type: string + x-go-custom-tag: gorm:"column:cloudnetworkname" + ProjectNetworkName: + type: string + x-go-custom-tag: gorm:"column:projectnetworkname" + HEAppEEndpoint: + type: string + x-go-custom-tag: gorm:"column:heappeendpoint" + HPCProvider: + type: string + enum: + - IT4I + - LRZ + - ICHEC + x-go-custom-tag: gorm:"column:hpcprovider" + OpenStackEndpoint: + type: string + x-go-custom-tag: gorm:"column:openstackendpoint" + OpenStackProjectID: + type: string + x-go-custom-tag: gorm:"column:openstackprojectid" + ResourceType: + type: string + enum: + - CLOUD + - HPC + x-go-custom-tag: gorm:"column:resourcetype" + TermsConsent: + type: boolean + x-go-custom-tag: gorm:"column:termsconsent;type:bool" + diff --git a/services/billing/README.md b/services/billing/README.md new file mode 100644 index 0000000..a3fd6fe --- /dev/null +++ b/services/billing/README.md @@ -0,0 +1,26 @@ +# BILLING SERVICE + +Cyclops Engine's Billing Service implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + diff --git a/services/billing/client/billing_management_api_client.go b/services/billing/client/billing_management_api_client.go new file mode 100644 index 0000000..9091847 --- /dev/null +++ b/services/billing/client/billing_management_api_client.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/client/bulk_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/client/invoice_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/client/trigger_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v1.0" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new billing management API HTTP client. +func New(c Config) *BillingManagementAPI { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(BillingManagementAPI) + cli.Transport = transport + cli.BulkManagement = bulk_management.New(transport, strfmt.Default, c.AuthInfo) + cli.InvoiceManagement = invoice_management.New(transport, strfmt.Default, c.AuthInfo) + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// BillingManagementAPI is a client for billing management API +type BillingManagementAPI struct { + BulkManagement *bulk_management.Client + InvoiceManagement *invoice_management.Client + StatusManagement *status_management.Client + TriggerManagement *trigger_management.Client + Transport runtime.ClientTransport +} diff --git a/services/billing/client/bulk_management/bulk_management_client.go b/services/billing/client/bulk_management/bulk_management_client.go new file mode 100644 index 0000000..df28644 --- /dev/null +++ b/services/billing/client/bulk_management/bulk_management_client.go @@ -0,0 +1,178 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the bulk management client +type API interface { + /* + GetBillRun gets the status report of the billrun requested*/ + GetBillRun(ctx context.Context, params *GetBillRunParams) (*GetBillRunOK, error) + /* + ListBillRuns shows the status report of the billruns present in the system*/ + ListBillRuns(ctx context.Context, params *ListBillRunsParams) (*ListBillRunsOK, error) + /* + ListBillRunsByOrganization shows the status report of the billruns present in the system*/ + ListBillRunsByOrganization(ctx context.Context, params *ListBillRunsByOrganizationParams) (*ListBillRunsByOrganizationOK, error) + /* + ReRunAllBillRuns tries to re run the failed invoices in all the billruns*/ + ReRunAllBillRuns(ctx context.Context, params *ReRunAllBillRunsParams) (*ReRunAllBillRunsAccepted, error) + /* + ReRunBillRun tries to re run the failed invoices in the billrun*/ + ReRunBillRun(ctx context.Context, params *ReRunBillRunParams) (*ReRunBillRunAccepted, error) +} + +// New creates a new bulk management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for bulk management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetBillRun gets the status report of the billrun requested +*/ +func (a *Client) GetBillRun(ctx context.Context, params *GetBillRunParams) (*GetBillRunOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "GetBillRun", + Method: "GET", + PathPattern: "/billrun/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetBillRunReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetBillRunOK), nil + +} + +/* +ListBillRuns shows the status report of the billruns present in the system +*/ +func (a *Client) ListBillRuns(ctx context.Context, params *ListBillRunsParams) (*ListBillRunsOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "ListBillRuns", + Method: "GET", + PathPattern: "/billrun", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListBillRunsReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListBillRunsOK), nil + +} + +/* +ListBillRunsByOrganization shows the status report of the billruns present in the system +*/ +func (a *Client) ListBillRunsByOrganization(ctx context.Context, params *ListBillRunsByOrganizationParams) (*ListBillRunsByOrganizationOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "ListBillRunsByOrganization", + Method: "GET", + PathPattern: "/billrun/organization/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListBillRunsByOrganizationReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListBillRunsByOrganizationOK), nil + +} + +/* +ReRunAllBillRuns tries to re run the failed invoices in all the billruns +*/ +func (a *Client) ReRunAllBillRuns(ctx context.Context, params *ReRunAllBillRunsParams) (*ReRunAllBillRunsAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "ReRunAllBillRuns", + Method: "PUT", + PathPattern: "/billrun", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ReRunAllBillRunsReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ReRunAllBillRunsAccepted), nil + +} + +/* +ReRunBillRun tries to re run the failed invoices in the billrun +*/ +func (a *Client) ReRunBillRun(ctx context.Context, params *ReRunBillRunParams) (*ReRunBillRunAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "ReRunBillRun", + Method: "PUT", + PathPattern: "/billrun/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ReRunBillRunReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ReRunBillRunAccepted), nil + +} diff --git a/services/billing/client/bulk_management/get_bill_run_parameters.go b/services/billing/client/bulk_management/get_bill_run_parameters.go new file mode 100644 index 0000000..997dd4d --- /dev/null +++ b/services/billing/client/bulk_management/get_bill_run_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetBillRunParams creates a new GetBillRunParams object +// with the default values initialized. +func NewGetBillRunParams() *GetBillRunParams { + var () + return &GetBillRunParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetBillRunParamsWithTimeout creates a new GetBillRunParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetBillRunParamsWithTimeout(timeout time.Duration) *GetBillRunParams { + var () + return &GetBillRunParams{ + + timeout: timeout, + } +} + +// NewGetBillRunParamsWithContext creates a new GetBillRunParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetBillRunParamsWithContext(ctx context.Context) *GetBillRunParams { + var () + return &GetBillRunParams{ + + Context: ctx, + } +} + +// NewGetBillRunParamsWithHTTPClient creates a new GetBillRunParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetBillRunParamsWithHTTPClient(client *http.Client) *GetBillRunParams { + var () + return &GetBillRunParams{ + HTTPClient: client, + } +} + +/*GetBillRunParams contains all the parameters to send to the API endpoint +for the get bill run operation typically these are written to a http.Request +*/ +type GetBillRunParams struct { + + /*ID + Id of the invoice to be checked + + */ + ID strfmt.UUID + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get bill run params +func (o *GetBillRunParams) WithTimeout(timeout time.Duration) *GetBillRunParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get bill run params +func (o *GetBillRunParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get bill run params +func (o *GetBillRunParams) WithContext(ctx context.Context) *GetBillRunParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get bill run params +func (o *GetBillRunParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get bill run params +func (o *GetBillRunParams) WithHTTPClient(client *http.Client) *GetBillRunParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get bill run params +func (o *GetBillRunParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get bill run params +func (o *GetBillRunParams) WithID(id strfmt.UUID) *GetBillRunParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get bill run params +func (o *GetBillRunParams) SetID(id strfmt.UUID) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetBillRunParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID.String()); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/bulk_management/get_bill_run_responses.go b/services/billing/client/bulk_management/get_bill_run_responses.go new file mode 100644 index 0000000..41909cc --- /dev/null +++ b/services/billing/client/bulk_management/get_bill_run_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetBillRunReader is a Reader for the GetBillRun structure. +type GetBillRunReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetBillRunReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetBillRunOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetBillRunNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetBillRunInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetBillRunOK creates a GetBillRunOK with default headers values +func NewGetBillRunOK() *GetBillRunOK { + return &GetBillRunOK{} +} + +/*GetBillRunOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetBillRunOK struct { + Payload *models.BillRunReport +} + +func (o *GetBillRunOK) Error() string { + return fmt.Sprintf("[GET /billrun/{id}][%d] getBillRunOK %+v", 200, o.Payload) +} + +func (o *GetBillRunOK) GetPayload() *models.BillRunReport { + return o.Payload +} + +func (o *GetBillRunOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.BillRunReport) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetBillRunNotFound creates a GetBillRunNotFound with default headers values +func NewGetBillRunNotFound() *GetBillRunNotFound { + return &GetBillRunNotFound{} +} + +/*GetBillRunNotFound handles this case with default header values. + +The invoice id provided doesn't exist +*/ +type GetBillRunNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetBillRunNotFound) Error() string { + return fmt.Sprintf("[GET /billrun/{id}][%d] getBillRunNotFound %+v", 404, o.Payload) +} + +func (o *GetBillRunNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetBillRunNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetBillRunInternalServerError creates a GetBillRunInternalServerError with default headers values +func NewGetBillRunInternalServerError() *GetBillRunInternalServerError { + return &GetBillRunInternalServerError{} +} + +/*GetBillRunInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetBillRunInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetBillRunInternalServerError) Error() string { + return fmt.Sprintf("[GET /billrun/{id}][%d] getBillRunInternalServerError %+v", 500, o.Payload) +} + +func (o *GetBillRunInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetBillRunInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/bulk_management/list_bill_runs_by_organization_parameters.go b/services/billing/client/bulk_management/list_bill_runs_by_organization_parameters.go new file mode 100644 index 0000000..81a915f --- /dev/null +++ b/services/billing/client/bulk_management/list_bill_runs_by_organization_parameters.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewListBillRunsByOrganizationParams creates a new ListBillRunsByOrganizationParams object +// with the default values initialized. +func NewListBillRunsByOrganizationParams() *ListBillRunsByOrganizationParams { + var () + return &ListBillRunsByOrganizationParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListBillRunsByOrganizationParamsWithTimeout creates a new ListBillRunsByOrganizationParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListBillRunsByOrganizationParamsWithTimeout(timeout time.Duration) *ListBillRunsByOrganizationParams { + var () + return &ListBillRunsByOrganizationParams{ + + timeout: timeout, + } +} + +// NewListBillRunsByOrganizationParamsWithContext creates a new ListBillRunsByOrganizationParams object +// with the default values initialized, and the ability to set a context for a request +func NewListBillRunsByOrganizationParamsWithContext(ctx context.Context) *ListBillRunsByOrganizationParams { + var () + return &ListBillRunsByOrganizationParams{ + + Context: ctx, + } +} + +// NewListBillRunsByOrganizationParamsWithHTTPClient creates a new ListBillRunsByOrganizationParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListBillRunsByOrganizationParamsWithHTTPClient(client *http.Client) *ListBillRunsByOrganizationParams { + var () + return &ListBillRunsByOrganizationParams{ + HTTPClient: client, + } +} + +/*ListBillRunsByOrganizationParams contains all the parameters to send to the API endpoint +for the list bill runs by organization operation typically these are written to a http.Request +*/ +type ListBillRunsByOrganizationParams struct { + + /*ID + Id of the billrun to be re-run. + + */ + ID string + /*Months + Amount of months to have in the report + + */ + Months *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) WithTimeout(timeout time.Duration) *ListBillRunsByOrganizationParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) WithContext(ctx context.Context) *ListBillRunsByOrganizationParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) WithHTTPClient(client *http.Client) *ListBillRunsByOrganizationParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) WithID(id string) *ListBillRunsByOrganizationParams { + o.SetID(id) + return o +} + +// SetID adds the id to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) SetID(id string) { + o.ID = id +} + +// WithMonths adds the months to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) WithMonths(months *int64) *ListBillRunsByOrganizationParams { + o.SetMonths(months) + return o +} + +// SetMonths adds the months to the list bill runs by organization params +func (o *ListBillRunsByOrganizationParams) SetMonths(months *int64) { + o.Months = months +} + +// WriteToRequest writes these params to a swagger request +func (o *ListBillRunsByOrganizationParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Months != nil { + + // query param months + var qrMonths int64 + if o.Months != nil { + qrMonths = *o.Months + } + qMonths := swag.FormatInt64(qrMonths) + if qMonths != "" { + if err := r.SetQueryParam("months", qMonths); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/bulk_management/list_bill_runs_by_organization_responses.go b/services/billing/client/bulk_management/list_bill_runs_by_organization_responses.go new file mode 100644 index 0000000..30820ef --- /dev/null +++ b/services/billing/client/bulk_management/list_bill_runs_by_organization_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListBillRunsByOrganizationReader is a Reader for the ListBillRunsByOrganization structure. +type ListBillRunsByOrganizationReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListBillRunsByOrganizationReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListBillRunsByOrganizationOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListBillRunsByOrganizationInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListBillRunsByOrganizationOK creates a ListBillRunsByOrganizationOK with default headers values +func NewListBillRunsByOrganizationOK() *ListBillRunsByOrganizationOK { + return &ListBillRunsByOrganizationOK{} +} + +/*ListBillRunsByOrganizationOK handles this case with default header values. + +Description of a successfully operation +*/ +type ListBillRunsByOrganizationOK struct { + Payload []*models.BillRunList +} + +func (o *ListBillRunsByOrganizationOK) Error() string { + return fmt.Sprintf("[GET /billrun/organization/{id}][%d] listBillRunsByOrganizationOK %+v", 200, o.Payload) +} + +func (o *ListBillRunsByOrganizationOK) GetPayload() []*models.BillRunList { + return o.Payload +} + +func (o *ListBillRunsByOrganizationOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListBillRunsByOrganizationInternalServerError creates a ListBillRunsByOrganizationInternalServerError with default headers values +func NewListBillRunsByOrganizationInternalServerError() *ListBillRunsByOrganizationInternalServerError { + return &ListBillRunsByOrganizationInternalServerError{} +} + +/*ListBillRunsByOrganizationInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListBillRunsByOrganizationInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListBillRunsByOrganizationInternalServerError) Error() string { + return fmt.Sprintf("[GET /billrun/organization/{id}][%d] listBillRunsByOrganizationInternalServerError %+v", 500, o.Payload) +} + +func (o *ListBillRunsByOrganizationInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListBillRunsByOrganizationInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/bulk_management/list_bill_runs_parameters.go b/services/billing/client/bulk_management/list_bill_runs_parameters.go new file mode 100644 index 0000000..67b1960 --- /dev/null +++ b/services/billing/client/bulk_management/list_bill_runs_parameters.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewListBillRunsParams creates a new ListBillRunsParams object +// with the default values initialized. +func NewListBillRunsParams() *ListBillRunsParams { + var () + return &ListBillRunsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListBillRunsParamsWithTimeout creates a new ListBillRunsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListBillRunsParamsWithTimeout(timeout time.Duration) *ListBillRunsParams { + var () + return &ListBillRunsParams{ + + timeout: timeout, + } +} + +// NewListBillRunsParamsWithContext creates a new ListBillRunsParams object +// with the default values initialized, and the ability to set a context for a request +func NewListBillRunsParamsWithContext(ctx context.Context) *ListBillRunsParams { + var () + return &ListBillRunsParams{ + + Context: ctx, + } +} + +// NewListBillRunsParamsWithHTTPClient creates a new ListBillRunsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListBillRunsParamsWithHTTPClient(client *http.Client) *ListBillRunsParams { + var () + return &ListBillRunsParams{ + HTTPClient: client, + } +} + +/*ListBillRunsParams contains all the parameters to send to the API endpoint +for the list bill runs operation typically these are written to a http.Request +*/ +type ListBillRunsParams struct { + + /*Months + Amount of months to have in the report + + */ + Months *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list bill runs params +func (o *ListBillRunsParams) WithTimeout(timeout time.Duration) *ListBillRunsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list bill runs params +func (o *ListBillRunsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list bill runs params +func (o *ListBillRunsParams) WithContext(ctx context.Context) *ListBillRunsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list bill runs params +func (o *ListBillRunsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list bill runs params +func (o *ListBillRunsParams) WithHTTPClient(client *http.Client) *ListBillRunsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list bill runs params +func (o *ListBillRunsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithMonths adds the months to the list bill runs params +func (o *ListBillRunsParams) WithMonths(months *int64) *ListBillRunsParams { + o.SetMonths(months) + return o +} + +// SetMonths adds the months to the list bill runs params +func (o *ListBillRunsParams) SetMonths(months *int64) { + o.Months = months +} + +// WriteToRequest writes these params to a swagger request +func (o *ListBillRunsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Months != nil { + + // query param months + var qrMonths int64 + if o.Months != nil { + qrMonths = *o.Months + } + qMonths := swag.FormatInt64(qrMonths) + if qMonths != "" { + if err := r.SetQueryParam("months", qMonths); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/bulk_management/list_bill_runs_responses.go b/services/billing/client/bulk_management/list_bill_runs_responses.go new file mode 100644 index 0000000..6d80f02 --- /dev/null +++ b/services/billing/client/bulk_management/list_bill_runs_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListBillRunsReader is a Reader for the ListBillRuns structure. +type ListBillRunsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListBillRunsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListBillRunsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListBillRunsInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListBillRunsOK creates a ListBillRunsOK with default headers values +func NewListBillRunsOK() *ListBillRunsOK { + return &ListBillRunsOK{} +} + +/*ListBillRunsOK handles this case with default header values. + +Description of a successfully operation +*/ +type ListBillRunsOK struct { + Payload []*models.BillRunList +} + +func (o *ListBillRunsOK) Error() string { + return fmt.Sprintf("[GET /billrun][%d] listBillRunsOK %+v", 200, o.Payload) +} + +func (o *ListBillRunsOK) GetPayload() []*models.BillRunList { + return o.Payload +} + +func (o *ListBillRunsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListBillRunsInternalServerError creates a ListBillRunsInternalServerError with default headers values +func NewListBillRunsInternalServerError() *ListBillRunsInternalServerError { + return &ListBillRunsInternalServerError{} +} + +/*ListBillRunsInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListBillRunsInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListBillRunsInternalServerError) Error() string { + return fmt.Sprintf("[GET /billrun][%d] listBillRunsInternalServerError %+v", 500, o.Payload) +} + +func (o *ListBillRunsInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListBillRunsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/bulk_management/re_run_all_bill_runs_parameters.go b/services/billing/client/bulk_management/re_run_all_bill_runs_parameters.go new file mode 100644 index 0000000..99aa06f --- /dev/null +++ b/services/billing/client/bulk_management/re_run_all_bill_runs_parameters.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewReRunAllBillRunsParams creates a new ReRunAllBillRunsParams object +// with the default values initialized. +func NewReRunAllBillRunsParams() *ReRunAllBillRunsParams { + var () + return &ReRunAllBillRunsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewReRunAllBillRunsParamsWithTimeout creates a new ReRunAllBillRunsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewReRunAllBillRunsParamsWithTimeout(timeout time.Duration) *ReRunAllBillRunsParams { + var () + return &ReRunAllBillRunsParams{ + + timeout: timeout, + } +} + +// NewReRunAllBillRunsParamsWithContext creates a new ReRunAllBillRunsParams object +// with the default values initialized, and the ability to set a context for a request +func NewReRunAllBillRunsParamsWithContext(ctx context.Context) *ReRunAllBillRunsParams { + var () + return &ReRunAllBillRunsParams{ + + Context: ctx, + } +} + +// NewReRunAllBillRunsParamsWithHTTPClient creates a new ReRunAllBillRunsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewReRunAllBillRunsParamsWithHTTPClient(client *http.Client) *ReRunAllBillRunsParams { + var () + return &ReRunAllBillRunsParams{ + HTTPClient: client, + } +} + +/*ReRunAllBillRunsParams contains all the parameters to send to the API endpoint +for the re run all bill runs operation typically these are written to a http.Request +*/ +type ReRunAllBillRunsParams struct { + + /*Months + Amount of months to check for failed invoices. + + */ + Months *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the re run all bill runs params +func (o *ReRunAllBillRunsParams) WithTimeout(timeout time.Duration) *ReRunAllBillRunsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the re run all bill runs params +func (o *ReRunAllBillRunsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the re run all bill runs params +func (o *ReRunAllBillRunsParams) WithContext(ctx context.Context) *ReRunAllBillRunsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the re run all bill runs params +func (o *ReRunAllBillRunsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the re run all bill runs params +func (o *ReRunAllBillRunsParams) WithHTTPClient(client *http.Client) *ReRunAllBillRunsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the re run all bill runs params +func (o *ReRunAllBillRunsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithMonths adds the months to the re run all bill runs params +func (o *ReRunAllBillRunsParams) WithMonths(months *int64) *ReRunAllBillRunsParams { + o.SetMonths(months) + return o +} + +// SetMonths adds the months to the re run all bill runs params +func (o *ReRunAllBillRunsParams) SetMonths(months *int64) { + o.Months = months +} + +// WriteToRequest writes these params to a swagger request +func (o *ReRunAllBillRunsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Months != nil { + + // query param months + var qrMonths int64 + if o.Months != nil { + qrMonths = *o.Months + } + qMonths := swag.FormatInt64(qrMonths) + if qMonths != "" { + if err := r.SetQueryParam("months", qMonths); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/bulk_management/re_run_all_bill_runs_responses.go b/services/billing/client/bulk_management/re_run_all_bill_runs_responses.go new file mode 100644 index 0000000..8f35489 --- /dev/null +++ b/services/billing/client/bulk_management/re_run_all_bill_runs_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ReRunAllBillRunsReader is a Reader for the ReRunAllBillRuns structure. +type ReRunAllBillRunsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ReRunAllBillRunsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 202: + result := NewReRunAllBillRunsAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewReRunAllBillRunsNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewReRunAllBillRunsInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewReRunAllBillRunsAccepted creates a ReRunAllBillRunsAccepted with default headers values +func NewReRunAllBillRunsAccepted() *ReRunAllBillRunsAccepted { + return &ReRunAllBillRunsAccepted{} +} + +/*ReRunAllBillRunsAccepted handles this case with default header values. + +The request for processing had been added to the queue +*/ +type ReRunAllBillRunsAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *ReRunAllBillRunsAccepted) Error() string { + return fmt.Sprintf("[PUT /billrun][%d] reRunAllBillRunsAccepted %+v", 202, o.Payload) +} + +func (o *ReRunAllBillRunsAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *ReRunAllBillRunsAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReRunAllBillRunsNotFound creates a ReRunAllBillRunsNotFound with default headers values +func NewReRunAllBillRunsNotFound() *ReRunAllBillRunsNotFound { + return &ReRunAllBillRunsNotFound{} +} + +/*ReRunAllBillRunsNotFound handles this case with default header values. + +The invoice id provided doesn't exist +*/ +type ReRunAllBillRunsNotFound struct { + Payload *models.ErrorResponse +} + +func (o *ReRunAllBillRunsNotFound) Error() string { + return fmt.Sprintf("[PUT /billrun][%d] reRunAllBillRunsNotFound %+v", 404, o.Payload) +} + +func (o *ReRunAllBillRunsNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ReRunAllBillRunsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReRunAllBillRunsInternalServerError creates a ReRunAllBillRunsInternalServerError with default headers values +func NewReRunAllBillRunsInternalServerError() *ReRunAllBillRunsInternalServerError { + return &ReRunAllBillRunsInternalServerError{} +} + +/*ReRunAllBillRunsInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ReRunAllBillRunsInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ReRunAllBillRunsInternalServerError) Error() string { + return fmt.Sprintf("[PUT /billrun][%d] reRunAllBillRunsInternalServerError %+v", 500, o.Payload) +} + +func (o *ReRunAllBillRunsInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ReRunAllBillRunsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/bulk_management/re_run_bill_run_parameters.go b/services/billing/client/bulk_management/re_run_bill_run_parameters.go new file mode 100644 index 0000000..4b49fa3 --- /dev/null +++ b/services/billing/client/bulk_management/re_run_bill_run_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewReRunBillRunParams creates a new ReRunBillRunParams object +// with the default values initialized. +func NewReRunBillRunParams() *ReRunBillRunParams { + var () + return &ReRunBillRunParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewReRunBillRunParamsWithTimeout creates a new ReRunBillRunParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewReRunBillRunParamsWithTimeout(timeout time.Duration) *ReRunBillRunParams { + var () + return &ReRunBillRunParams{ + + timeout: timeout, + } +} + +// NewReRunBillRunParamsWithContext creates a new ReRunBillRunParams object +// with the default values initialized, and the ability to set a context for a request +func NewReRunBillRunParamsWithContext(ctx context.Context) *ReRunBillRunParams { + var () + return &ReRunBillRunParams{ + + Context: ctx, + } +} + +// NewReRunBillRunParamsWithHTTPClient creates a new ReRunBillRunParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewReRunBillRunParamsWithHTTPClient(client *http.Client) *ReRunBillRunParams { + var () + return &ReRunBillRunParams{ + HTTPClient: client, + } +} + +/*ReRunBillRunParams contains all the parameters to send to the API endpoint +for the re run bill run operation typically these are written to a http.Request +*/ +type ReRunBillRunParams struct { + + /*ID + Id of the billrun to be re-run. + + */ + ID strfmt.UUID + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the re run bill run params +func (o *ReRunBillRunParams) WithTimeout(timeout time.Duration) *ReRunBillRunParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the re run bill run params +func (o *ReRunBillRunParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the re run bill run params +func (o *ReRunBillRunParams) WithContext(ctx context.Context) *ReRunBillRunParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the re run bill run params +func (o *ReRunBillRunParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the re run bill run params +func (o *ReRunBillRunParams) WithHTTPClient(client *http.Client) *ReRunBillRunParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the re run bill run params +func (o *ReRunBillRunParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the re run bill run params +func (o *ReRunBillRunParams) WithID(id strfmt.UUID) *ReRunBillRunParams { + o.SetID(id) + return o +} + +// SetID adds the id to the re run bill run params +func (o *ReRunBillRunParams) SetID(id strfmt.UUID) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *ReRunBillRunParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID.String()); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/bulk_management/re_run_bill_run_responses.go b/services/billing/client/bulk_management/re_run_bill_run_responses.go new file mode 100644 index 0000000..35746f2 --- /dev/null +++ b/services/billing/client/bulk_management/re_run_bill_run_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ReRunBillRunReader is a Reader for the ReRunBillRun structure. +type ReRunBillRunReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ReRunBillRunReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 202: + result := NewReRunBillRunAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewReRunBillRunNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewReRunBillRunInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewReRunBillRunAccepted creates a ReRunBillRunAccepted with default headers values +func NewReRunBillRunAccepted() *ReRunBillRunAccepted { + return &ReRunBillRunAccepted{} +} + +/*ReRunBillRunAccepted handles this case with default header values. + +The request for processing had been added to the queue +*/ +type ReRunBillRunAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *ReRunBillRunAccepted) Error() string { + return fmt.Sprintf("[PUT /billrun/{id}][%d] reRunBillRunAccepted %+v", 202, o.Payload) +} + +func (o *ReRunBillRunAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *ReRunBillRunAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReRunBillRunNotFound creates a ReRunBillRunNotFound with default headers values +func NewReRunBillRunNotFound() *ReRunBillRunNotFound { + return &ReRunBillRunNotFound{} +} + +/*ReRunBillRunNotFound handles this case with default header values. + +The invoice id provided doesn't exist +*/ +type ReRunBillRunNotFound struct { + Payload *models.ErrorResponse +} + +func (o *ReRunBillRunNotFound) Error() string { + return fmt.Sprintf("[PUT /billrun/{id}][%d] reRunBillRunNotFound %+v", 404, o.Payload) +} + +func (o *ReRunBillRunNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ReRunBillRunNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewReRunBillRunInternalServerError creates a ReRunBillRunInternalServerError with default headers values +func NewReRunBillRunInternalServerError() *ReRunBillRunInternalServerError { + return &ReRunBillRunInternalServerError{} +} + +/*ReRunBillRunInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ReRunBillRunInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ReRunBillRunInternalServerError) Error() string { + return fmt.Sprintf("[PUT /billrun/{id}][%d] reRunBillRunInternalServerError %+v", 500, o.Payload) +} + +func (o *ReRunBillRunInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ReRunBillRunInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/generate_invoice_for_customer_parameters.go b/services/billing/client/invoice_management/generate_invoice_for_customer_parameters.go new file mode 100644 index 0000000..224739a --- /dev/null +++ b/services/billing/client/invoice_management/generate_invoice_for_customer_parameters.go @@ -0,0 +1,199 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGenerateInvoiceForCustomerParams creates a new GenerateInvoiceForCustomerParams object +// with the default values initialized. +func NewGenerateInvoiceForCustomerParams() *GenerateInvoiceForCustomerParams { + var () + return &GenerateInvoiceForCustomerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGenerateInvoiceForCustomerParamsWithTimeout creates a new GenerateInvoiceForCustomerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGenerateInvoiceForCustomerParamsWithTimeout(timeout time.Duration) *GenerateInvoiceForCustomerParams { + var () + return &GenerateInvoiceForCustomerParams{ + + timeout: timeout, + } +} + +// NewGenerateInvoiceForCustomerParamsWithContext creates a new GenerateInvoiceForCustomerParams object +// with the default values initialized, and the ability to set a context for a request +func NewGenerateInvoiceForCustomerParamsWithContext(ctx context.Context) *GenerateInvoiceForCustomerParams { + var () + return &GenerateInvoiceForCustomerParams{ + + Context: ctx, + } +} + +// NewGenerateInvoiceForCustomerParamsWithHTTPClient creates a new GenerateInvoiceForCustomerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGenerateInvoiceForCustomerParamsWithHTTPClient(client *http.Client) *GenerateInvoiceForCustomerParams { + var () + return &GenerateInvoiceForCustomerParams{ + HTTPClient: client, + } +} + +/*GenerateInvoiceForCustomerParams contains all the parameters to send to the API endpoint +for the generate invoice for customer operation typically these are written to a http.Request +*/ +type GenerateInvoiceForCustomerParams struct { + + /*From + Datetime from which to generate the invoice + + */ + From *strfmt.DateTime + /*ID + Id of the account to be checked + + */ + ID string + /*To + Datetime until which to generate the invoice + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) WithTimeout(timeout time.Duration) *GenerateInvoiceForCustomerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) WithContext(ctx context.Context) *GenerateInvoiceForCustomerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) WithHTTPClient(client *http.Client) *GenerateInvoiceForCustomerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) WithFrom(from *strfmt.DateTime) *GenerateInvoiceForCustomerParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithID adds the id to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) WithID(id string) *GenerateInvoiceForCustomerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) SetID(id string) { + o.ID = id +} + +// WithTo adds the to to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) WithTo(to *strfmt.DateTime) *GenerateInvoiceForCustomerParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the generate invoice for customer params +func (o *GenerateInvoiceForCustomerParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GenerateInvoiceForCustomerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/generate_invoice_for_customer_responses.go b/services/billing/client/invoice_management/generate_invoice_for_customer_responses.go new file mode 100644 index 0000000..e660d29 --- /dev/null +++ b/services/billing/client/invoice_management/generate_invoice_for_customer_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GenerateInvoiceForCustomerReader is a Reader for the GenerateInvoiceForCustomer structure. +type GenerateInvoiceForCustomerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GenerateInvoiceForCustomerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 202: + result := NewGenerateInvoiceForCustomerAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGenerateInvoiceForCustomerBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGenerateInvoiceForCustomerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGenerateInvoiceForCustomerAccepted creates a GenerateInvoiceForCustomerAccepted with default headers values +func NewGenerateInvoiceForCustomerAccepted() *GenerateInvoiceForCustomerAccepted { + return &GenerateInvoiceForCustomerAccepted{} +} + +/*GenerateInvoiceForCustomerAccepted handles this case with default header values. + +The request for processing had been added to the queue +*/ +type GenerateInvoiceForCustomerAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *GenerateInvoiceForCustomerAccepted) Error() string { + return fmt.Sprintf("[POST /invoice/customer/{id}][%d] generateInvoiceForCustomerAccepted %+v", 202, o.Payload) +} + +func (o *GenerateInvoiceForCustomerAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *GenerateInvoiceForCustomerAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGenerateInvoiceForCustomerBadRequest creates a GenerateInvoiceForCustomerBadRequest with default headers values +func NewGenerateInvoiceForCustomerBadRequest() *GenerateInvoiceForCustomerBadRequest { + return &GenerateInvoiceForCustomerBadRequest{} +} + +/*GenerateInvoiceForCustomerBadRequest handles this case with default header values. + +Invalid input, object invalid +*/ +type GenerateInvoiceForCustomerBadRequest struct { + Payload *models.ErrorResponse +} + +func (o *GenerateInvoiceForCustomerBadRequest) Error() string { + return fmt.Sprintf("[POST /invoice/customer/{id}][%d] generateInvoiceForCustomerBadRequest %+v", 400, o.Payload) +} + +func (o *GenerateInvoiceForCustomerBadRequest) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GenerateInvoiceForCustomerBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGenerateInvoiceForCustomerInternalServerError creates a GenerateInvoiceForCustomerInternalServerError with default headers values +func NewGenerateInvoiceForCustomerInternalServerError() *GenerateInvoiceForCustomerInternalServerError { + return &GenerateInvoiceForCustomerInternalServerError{} +} + +/*GenerateInvoiceForCustomerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GenerateInvoiceForCustomerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GenerateInvoiceForCustomerInternalServerError) Error() string { + return fmt.Sprintf("[POST /invoice/customer/{id}][%d] generateInvoiceForCustomerInternalServerError %+v", 500, o.Payload) +} + +func (o *GenerateInvoiceForCustomerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GenerateInvoiceForCustomerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/generate_invoice_for_reseller_parameters.go b/services/billing/client/invoice_management/generate_invoice_for_reseller_parameters.go new file mode 100644 index 0000000..1b0e449 --- /dev/null +++ b/services/billing/client/invoice_management/generate_invoice_for_reseller_parameters.go @@ -0,0 +1,199 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGenerateInvoiceForResellerParams creates a new GenerateInvoiceForResellerParams object +// with the default values initialized. +func NewGenerateInvoiceForResellerParams() *GenerateInvoiceForResellerParams { + var () + return &GenerateInvoiceForResellerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGenerateInvoiceForResellerParamsWithTimeout creates a new GenerateInvoiceForResellerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGenerateInvoiceForResellerParamsWithTimeout(timeout time.Duration) *GenerateInvoiceForResellerParams { + var () + return &GenerateInvoiceForResellerParams{ + + timeout: timeout, + } +} + +// NewGenerateInvoiceForResellerParamsWithContext creates a new GenerateInvoiceForResellerParams object +// with the default values initialized, and the ability to set a context for a request +func NewGenerateInvoiceForResellerParamsWithContext(ctx context.Context) *GenerateInvoiceForResellerParams { + var () + return &GenerateInvoiceForResellerParams{ + + Context: ctx, + } +} + +// NewGenerateInvoiceForResellerParamsWithHTTPClient creates a new GenerateInvoiceForResellerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGenerateInvoiceForResellerParamsWithHTTPClient(client *http.Client) *GenerateInvoiceForResellerParams { + var () + return &GenerateInvoiceForResellerParams{ + HTTPClient: client, + } +} + +/*GenerateInvoiceForResellerParams contains all the parameters to send to the API endpoint +for the generate invoice for reseller operation typically these are written to a http.Request +*/ +type GenerateInvoiceForResellerParams struct { + + /*From + Datetime from which to generate the invoice + + */ + From *strfmt.DateTime + /*ID + Id of the account to be checked + + */ + ID string + /*To + Datetime until which to generate the invoice + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) WithTimeout(timeout time.Duration) *GenerateInvoiceForResellerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) WithContext(ctx context.Context) *GenerateInvoiceForResellerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) WithHTTPClient(client *http.Client) *GenerateInvoiceForResellerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) WithFrom(from *strfmt.DateTime) *GenerateInvoiceForResellerParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithID adds the id to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) WithID(id string) *GenerateInvoiceForResellerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) SetID(id string) { + o.ID = id +} + +// WithTo adds the to to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) WithTo(to *strfmt.DateTime) *GenerateInvoiceForResellerParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the generate invoice for reseller params +func (o *GenerateInvoiceForResellerParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GenerateInvoiceForResellerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/generate_invoice_for_reseller_responses.go b/services/billing/client/invoice_management/generate_invoice_for_reseller_responses.go new file mode 100644 index 0000000..8f5c058 --- /dev/null +++ b/services/billing/client/invoice_management/generate_invoice_for_reseller_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GenerateInvoiceForResellerReader is a Reader for the GenerateInvoiceForReseller structure. +type GenerateInvoiceForResellerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GenerateInvoiceForResellerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 202: + result := NewGenerateInvoiceForResellerAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGenerateInvoiceForResellerBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGenerateInvoiceForResellerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGenerateInvoiceForResellerAccepted creates a GenerateInvoiceForResellerAccepted with default headers values +func NewGenerateInvoiceForResellerAccepted() *GenerateInvoiceForResellerAccepted { + return &GenerateInvoiceForResellerAccepted{} +} + +/*GenerateInvoiceForResellerAccepted handles this case with default header values. + +The request for processing had been added to the queue +*/ +type GenerateInvoiceForResellerAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *GenerateInvoiceForResellerAccepted) Error() string { + return fmt.Sprintf("[POST /invoice/reseller/{id}][%d] generateInvoiceForResellerAccepted %+v", 202, o.Payload) +} + +func (o *GenerateInvoiceForResellerAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *GenerateInvoiceForResellerAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGenerateInvoiceForResellerBadRequest creates a GenerateInvoiceForResellerBadRequest with default headers values +func NewGenerateInvoiceForResellerBadRequest() *GenerateInvoiceForResellerBadRequest { + return &GenerateInvoiceForResellerBadRequest{} +} + +/*GenerateInvoiceForResellerBadRequest handles this case with default header values. + +Invalid input, object invalid +*/ +type GenerateInvoiceForResellerBadRequest struct { + Payload *models.ErrorResponse +} + +func (o *GenerateInvoiceForResellerBadRequest) Error() string { + return fmt.Sprintf("[POST /invoice/reseller/{id}][%d] generateInvoiceForResellerBadRequest %+v", 400, o.Payload) +} + +func (o *GenerateInvoiceForResellerBadRequest) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GenerateInvoiceForResellerBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGenerateInvoiceForResellerInternalServerError creates a GenerateInvoiceForResellerInternalServerError with default headers values +func NewGenerateInvoiceForResellerInternalServerError() *GenerateInvoiceForResellerInternalServerError { + return &GenerateInvoiceForResellerInternalServerError{} +} + +/*GenerateInvoiceForResellerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GenerateInvoiceForResellerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GenerateInvoiceForResellerInternalServerError) Error() string { + return fmt.Sprintf("[POST /invoice/reseller/{id}][%d] generateInvoiceForResellerInternalServerError %+v", 500, o.Payload) +} + +func (o *GenerateInvoiceForResellerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GenerateInvoiceForResellerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/get_invoice_parameters.go b/services/billing/client/invoice_management/get_invoice_parameters.go new file mode 100644 index 0000000..3e51626 --- /dev/null +++ b/services/billing/client/invoice_management/get_invoice_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetInvoiceParams creates a new GetInvoiceParams object +// with the default values initialized. +func NewGetInvoiceParams() *GetInvoiceParams { + var () + return &GetInvoiceParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetInvoiceParamsWithTimeout creates a new GetInvoiceParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetInvoiceParamsWithTimeout(timeout time.Duration) *GetInvoiceParams { + var () + return &GetInvoiceParams{ + + timeout: timeout, + } +} + +// NewGetInvoiceParamsWithContext creates a new GetInvoiceParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetInvoiceParamsWithContext(ctx context.Context) *GetInvoiceParams { + var () + return &GetInvoiceParams{ + + Context: ctx, + } +} + +// NewGetInvoiceParamsWithHTTPClient creates a new GetInvoiceParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetInvoiceParamsWithHTTPClient(client *http.Client) *GetInvoiceParams { + var () + return &GetInvoiceParams{ + HTTPClient: client, + } +} + +/*GetInvoiceParams contains all the parameters to send to the API endpoint +for the get invoice operation typically these are written to a http.Request +*/ +type GetInvoiceParams struct { + + /*ID + Id of the invoice to be checked + + */ + ID strfmt.UUID + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get invoice params +func (o *GetInvoiceParams) WithTimeout(timeout time.Duration) *GetInvoiceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get invoice params +func (o *GetInvoiceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get invoice params +func (o *GetInvoiceParams) WithContext(ctx context.Context) *GetInvoiceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get invoice params +func (o *GetInvoiceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get invoice params +func (o *GetInvoiceParams) WithHTTPClient(client *http.Client) *GetInvoiceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get invoice params +func (o *GetInvoiceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get invoice params +func (o *GetInvoiceParams) WithID(id strfmt.UUID) *GetInvoiceParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get invoice params +func (o *GetInvoiceParams) SetID(id strfmt.UUID) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetInvoiceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID.String()); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/get_invoice_responses.go b/services/billing/client/invoice_management/get_invoice_responses.go new file mode 100644 index 0000000..21a9b37 --- /dev/null +++ b/services/billing/client/invoice_management/get_invoice_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetInvoiceReader is a Reader for the GetInvoice structure. +type GetInvoiceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetInvoiceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetInvoiceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetInvoiceNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetInvoiceInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetInvoiceOK creates a GetInvoiceOK with default headers values +func NewGetInvoiceOK() *GetInvoiceOK { + return &GetInvoiceOK{} +} + +/*GetInvoiceOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetInvoiceOK struct { + Payload *models.Invoice +} + +func (o *GetInvoiceOK) Error() string { + return fmt.Sprintf("[GET /invoice/{id}][%d] getInvoiceOK %+v", 200, o.Payload) +} + +func (o *GetInvoiceOK) GetPayload() *models.Invoice { + return o.Payload +} + +func (o *GetInvoiceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Invoice) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInvoiceNotFound creates a GetInvoiceNotFound with default headers values +func NewGetInvoiceNotFound() *GetInvoiceNotFound { + return &GetInvoiceNotFound{} +} + +/*GetInvoiceNotFound handles this case with default header values. + +The invoice id provided doesn't exist +*/ +type GetInvoiceNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetInvoiceNotFound) Error() string { + return fmt.Sprintf("[GET /invoice/{id}][%d] getInvoiceNotFound %+v", 404, o.Payload) +} + +func (o *GetInvoiceNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetInvoiceNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInvoiceInternalServerError creates a GetInvoiceInternalServerError with default headers values +func NewGetInvoiceInternalServerError() *GetInvoiceInternalServerError { + return &GetInvoiceInternalServerError{} +} + +/*GetInvoiceInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetInvoiceInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetInvoiceInternalServerError) Error() string { + return fmt.Sprintf("[GET /invoice/{id}][%d] getInvoiceInternalServerError %+v", 500, o.Payload) +} + +func (o *GetInvoiceInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetInvoiceInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/get_invoices_by_customer_parameters.go b/services/billing/client/invoice_management/get_invoices_by_customer_parameters.go new file mode 100644 index 0000000..7f289de --- /dev/null +++ b/services/billing/client/invoice_management/get_invoices_by_customer_parameters.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetInvoicesByCustomerParams creates a new GetInvoicesByCustomerParams object +// with the default values initialized. +func NewGetInvoicesByCustomerParams() *GetInvoicesByCustomerParams { + var () + return &GetInvoicesByCustomerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetInvoicesByCustomerParamsWithTimeout creates a new GetInvoicesByCustomerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetInvoicesByCustomerParamsWithTimeout(timeout time.Duration) *GetInvoicesByCustomerParams { + var () + return &GetInvoicesByCustomerParams{ + + timeout: timeout, + } +} + +// NewGetInvoicesByCustomerParamsWithContext creates a new GetInvoicesByCustomerParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetInvoicesByCustomerParamsWithContext(ctx context.Context) *GetInvoicesByCustomerParams { + var () + return &GetInvoicesByCustomerParams{ + + Context: ctx, + } +} + +// NewGetInvoicesByCustomerParamsWithHTTPClient creates a new GetInvoicesByCustomerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetInvoicesByCustomerParamsWithHTTPClient(client *http.Client) *GetInvoicesByCustomerParams { + var () + return &GetInvoicesByCustomerParams{ + HTTPClient: client, + } +} + +/*GetInvoicesByCustomerParams contains all the parameters to send to the API endpoint +for the get invoices by customer operation typically these are written to a http.Request +*/ +type GetInvoicesByCustomerParams struct { + + /*ID + Id of the account to be checked + + */ + ID string + /*Months + Amount of months to have in the report + + */ + Months *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) WithTimeout(timeout time.Duration) *GetInvoicesByCustomerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) WithContext(ctx context.Context) *GetInvoicesByCustomerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) WithHTTPClient(client *http.Client) *GetInvoicesByCustomerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) WithID(id string) *GetInvoicesByCustomerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) SetID(id string) { + o.ID = id +} + +// WithMonths adds the months to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) WithMonths(months *int64) *GetInvoicesByCustomerParams { + o.SetMonths(months) + return o +} + +// SetMonths adds the months to the get invoices by customer params +func (o *GetInvoicesByCustomerParams) SetMonths(months *int64) { + o.Months = months +} + +// WriteToRequest writes these params to a swagger request +func (o *GetInvoicesByCustomerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Months != nil { + + // query param months + var qrMonths int64 + if o.Months != nil { + qrMonths = *o.Months + } + qMonths := swag.FormatInt64(qrMonths) + if qMonths != "" { + if err := r.SetQueryParam("months", qMonths); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/get_invoices_by_customer_responses.go b/services/billing/client/invoice_management/get_invoices_by_customer_responses.go new file mode 100644 index 0000000..10be5bb --- /dev/null +++ b/services/billing/client/invoice_management/get_invoices_by_customer_responses.go @@ -0,0 +1,145 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetInvoicesByCustomerReader is a Reader for the GetInvoicesByCustomer structure. +type GetInvoicesByCustomerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetInvoicesByCustomerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetInvoicesByCustomerOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetInvoicesByCustomerNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetInvoicesByCustomerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetInvoicesByCustomerOK creates a GetInvoicesByCustomerOK with default headers values +func NewGetInvoicesByCustomerOK() *GetInvoicesByCustomerOK { + return &GetInvoicesByCustomerOK{} +} + +/*GetInvoicesByCustomerOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetInvoicesByCustomerOK struct { + Payload []*models.Invoice +} + +func (o *GetInvoicesByCustomerOK) Error() string { + return fmt.Sprintf("[GET /invoice/customer/{id}][%d] getInvoicesByCustomerOK %+v", 200, o.Payload) +} + +func (o *GetInvoicesByCustomerOK) GetPayload() []*models.Invoice { + return o.Payload +} + +func (o *GetInvoicesByCustomerOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInvoicesByCustomerNotFound creates a GetInvoicesByCustomerNotFound with default headers values +func NewGetInvoicesByCustomerNotFound() *GetInvoicesByCustomerNotFound { + return &GetInvoicesByCustomerNotFound{} +} + +/*GetInvoicesByCustomerNotFound handles this case with default header values. + +The invoice id provided doesn't exist +*/ +type GetInvoicesByCustomerNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetInvoicesByCustomerNotFound) Error() string { + return fmt.Sprintf("[GET /invoice/customer/{id}][%d] getInvoicesByCustomerNotFound %+v", 404, o.Payload) +} + +func (o *GetInvoicesByCustomerNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetInvoicesByCustomerNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInvoicesByCustomerInternalServerError creates a GetInvoicesByCustomerInternalServerError with default headers values +func NewGetInvoicesByCustomerInternalServerError() *GetInvoicesByCustomerInternalServerError { + return &GetInvoicesByCustomerInternalServerError{} +} + +/*GetInvoicesByCustomerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetInvoicesByCustomerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetInvoicesByCustomerInternalServerError) Error() string { + return fmt.Sprintf("[GET /invoice/customer/{id}][%d] getInvoicesByCustomerInternalServerError %+v", 500, o.Payload) +} + +func (o *GetInvoicesByCustomerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetInvoicesByCustomerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/get_invoices_by_reseller_parameters.go b/services/billing/client/invoice_management/get_invoices_by_reseller_parameters.go new file mode 100644 index 0000000..6869a5c --- /dev/null +++ b/services/billing/client/invoice_management/get_invoices_by_reseller_parameters.go @@ -0,0 +1,168 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetInvoicesByResellerParams creates a new GetInvoicesByResellerParams object +// with the default values initialized. +func NewGetInvoicesByResellerParams() *GetInvoicesByResellerParams { + var () + return &GetInvoicesByResellerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetInvoicesByResellerParamsWithTimeout creates a new GetInvoicesByResellerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetInvoicesByResellerParamsWithTimeout(timeout time.Duration) *GetInvoicesByResellerParams { + var () + return &GetInvoicesByResellerParams{ + + timeout: timeout, + } +} + +// NewGetInvoicesByResellerParamsWithContext creates a new GetInvoicesByResellerParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetInvoicesByResellerParamsWithContext(ctx context.Context) *GetInvoicesByResellerParams { + var () + return &GetInvoicesByResellerParams{ + + Context: ctx, + } +} + +// NewGetInvoicesByResellerParamsWithHTTPClient creates a new GetInvoicesByResellerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetInvoicesByResellerParamsWithHTTPClient(client *http.Client) *GetInvoicesByResellerParams { + var () + return &GetInvoicesByResellerParams{ + HTTPClient: client, + } +} + +/*GetInvoicesByResellerParams contains all the parameters to send to the API endpoint +for the get invoices by reseller operation typically these are written to a http.Request +*/ +type GetInvoicesByResellerParams struct { + + /*ID + Id of the account to be checked + + */ + ID string + /*Months + Amount of months to have in the report + + */ + Months *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) WithTimeout(timeout time.Duration) *GetInvoicesByResellerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) WithContext(ctx context.Context) *GetInvoicesByResellerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) WithHTTPClient(client *http.Client) *GetInvoicesByResellerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) WithID(id string) *GetInvoicesByResellerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) SetID(id string) { + o.ID = id +} + +// WithMonths adds the months to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) WithMonths(months *int64) *GetInvoicesByResellerParams { + o.SetMonths(months) + return o +} + +// SetMonths adds the months to the get invoices by reseller params +func (o *GetInvoicesByResellerParams) SetMonths(months *int64) { + o.Months = months +} + +// WriteToRequest writes these params to a swagger request +func (o *GetInvoicesByResellerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Months != nil { + + // query param months + var qrMonths int64 + if o.Months != nil { + qrMonths = *o.Months + } + qMonths := swag.FormatInt64(qrMonths) + if qMonths != "" { + if err := r.SetQueryParam("months", qMonths); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/get_invoices_by_reseller_responses.go b/services/billing/client/invoice_management/get_invoices_by_reseller_responses.go new file mode 100644 index 0000000..de6a763 --- /dev/null +++ b/services/billing/client/invoice_management/get_invoices_by_reseller_responses.go @@ -0,0 +1,145 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetInvoicesByResellerReader is a Reader for the GetInvoicesByReseller structure. +type GetInvoicesByResellerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetInvoicesByResellerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetInvoicesByResellerOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetInvoicesByResellerNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetInvoicesByResellerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetInvoicesByResellerOK creates a GetInvoicesByResellerOK with default headers values +func NewGetInvoicesByResellerOK() *GetInvoicesByResellerOK { + return &GetInvoicesByResellerOK{} +} + +/*GetInvoicesByResellerOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetInvoicesByResellerOK struct { + Payload []*models.Invoice +} + +func (o *GetInvoicesByResellerOK) Error() string { + return fmt.Sprintf("[GET /invoice/reseller/{id}][%d] getInvoicesByResellerOK %+v", 200, o.Payload) +} + +func (o *GetInvoicesByResellerOK) GetPayload() []*models.Invoice { + return o.Payload +} + +func (o *GetInvoicesByResellerOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInvoicesByResellerNotFound creates a GetInvoicesByResellerNotFound with default headers values +func NewGetInvoicesByResellerNotFound() *GetInvoicesByResellerNotFound { + return &GetInvoicesByResellerNotFound{} +} + +/*GetInvoicesByResellerNotFound handles this case with default header values. + +The invoice id provided doesn't exist +*/ +type GetInvoicesByResellerNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetInvoicesByResellerNotFound) Error() string { + return fmt.Sprintf("[GET /invoice/reseller/{id}][%d] getInvoicesByResellerNotFound %+v", 404, o.Payload) +} + +func (o *GetInvoicesByResellerNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetInvoicesByResellerNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetInvoicesByResellerInternalServerError creates a GetInvoicesByResellerInternalServerError with default headers values +func NewGetInvoicesByResellerInternalServerError() *GetInvoicesByResellerInternalServerError { + return &GetInvoicesByResellerInternalServerError{} +} + +/*GetInvoicesByResellerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetInvoicesByResellerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetInvoicesByResellerInternalServerError) Error() string { + return fmt.Sprintf("[GET /invoice/reseller/{id}][%d] getInvoicesByResellerInternalServerError %+v", 500, o.Payload) +} + +func (o *GetInvoicesByResellerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetInvoicesByResellerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/invoice_management_client.go b/services/billing/client/invoice_management/invoice_management_client.go new file mode 100644 index 0000000..39b054e --- /dev/null +++ b/services/billing/client/invoice_management/invoice_management_client.go @@ -0,0 +1,262 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the invoice management client +type API interface { + /* + GenerateInvoiceForCustomer generates invoice for the provided customer for the provided time window or last period*/ + GenerateInvoiceForCustomer(ctx context.Context, params *GenerateInvoiceForCustomerParams) (*GenerateInvoiceForCustomerAccepted, error) + /* + GenerateInvoiceForReseller generates invoice for the provided reseller for the provided time window or last period*/ + GenerateInvoiceForReseller(ctx context.Context, params *GenerateInvoiceForResellerParams) (*GenerateInvoiceForResellerAccepted, error) + /* + GetInvoice summaries for this endpoint*/ + GetInvoice(ctx context.Context, params *GetInvoiceParams) (*GetInvoiceOK, error) + /* + GetInvoicesByCustomer retrieves invoices by customer id*/ + GetInvoicesByCustomer(ctx context.Context, params *GetInvoicesByCustomerParams) (*GetInvoicesByCustomerOK, error) + /* + GetInvoicesByReseller retrieves invoices by reseller id*/ + GetInvoicesByReseller(ctx context.Context, params *GetInvoicesByResellerParams) (*GetInvoicesByResellerOK, error) + /* + ListCustomerInvoices retrieves customers invoices*/ + ListCustomerInvoices(ctx context.Context, params *ListCustomerInvoicesParams) (*ListCustomerInvoicesOK, error) + /* + ListInvoices summaries for this endpoint*/ + ListInvoices(ctx context.Context, params *ListInvoicesParams) (*ListInvoicesOK, error) + /* + ListResellerInvoices retrieves resellers invoices*/ + ListResellerInvoices(ctx context.Context, params *ListResellerInvoicesParams) (*ListResellerInvoicesOK, error) +} + +// New creates a new invoice management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for invoice management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GenerateInvoiceForCustomer generates invoice for the provided customer for the provided time window or last period +*/ +func (a *Client) GenerateInvoiceForCustomer(ctx context.Context, params *GenerateInvoiceForCustomerParams) (*GenerateInvoiceForCustomerAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "GenerateInvoiceForCustomer", + Method: "POST", + PathPattern: "/invoice/customer/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GenerateInvoiceForCustomerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GenerateInvoiceForCustomerAccepted), nil + +} + +/* +GenerateInvoiceForReseller generates invoice for the provided reseller for the provided time window or last period +*/ +func (a *Client) GenerateInvoiceForReseller(ctx context.Context, params *GenerateInvoiceForResellerParams) (*GenerateInvoiceForResellerAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "GenerateInvoiceForReseller", + Method: "POST", + PathPattern: "/invoice/reseller/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GenerateInvoiceForResellerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GenerateInvoiceForResellerAccepted), nil + +} + +/* +GetInvoice summaries for this endpoint +*/ +func (a *Client) GetInvoice(ctx context.Context, params *GetInvoiceParams) (*GetInvoiceOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "GetInvoice", + Method: "GET", + PathPattern: "/invoice/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetInvoiceReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetInvoiceOK), nil + +} + +/* +GetInvoicesByCustomer retrieves invoices by customer id +*/ +func (a *Client) GetInvoicesByCustomer(ctx context.Context, params *GetInvoicesByCustomerParams) (*GetInvoicesByCustomerOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "GetInvoicesByCustomer", + Method: "GET", + PathPattern: "/invoice/customer/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetInvoicesByCustomerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetInvoicesByCustomerOK), nil + +} + +/* +GetInvoicesByReseller retrieves invoices by reseller id +*/ +func (a *Client) GetInvoicesByReseller(ctx context.Context, params *GetInvoicesByResellerParams) (*GetInvoicesByResellerOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "GetInvoicesByReseller", + Method: "GET", + PathPattern: "/invoice/reseller/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetInvoicesByResellerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetInvoicesByResellerOK), nil + +} + +/* +ListCustomerInvoices retrieves customers invoices +*/ +func (a *Client) ListCustomerInvoices(ctx context.Context, params *ListCustomerInvoicesParams) (*ListCustomerInvoicesOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "ListCustomerInvoices", + Method: "GET", + PathPattern: "/invoice/customer", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListCustomerInvoicesReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListCustomerInvoicesOK), nil + +} + +/* +ListInvoices summaries for this endpoint +*/ +func (a *Client) ListInvoices(ctx context.Context, params *ListInvoicesParams) (*ListInvoicesOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "ListInvoices", + Method: "GET", + PathPattern: "/invoice", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListInvoicesReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListInvoicesOK), nil + +} + +/* +ListResellerInvoices retrieves resellers invoices +*/ +func (a *Client) ListResellerInvoices(ctx context.Context, params *ListResellerInvoicesParams) (*ListResellerInvoicesOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "ListResellerInvoices", + Method: "GET", + PathPattern: "/invoice/reseller", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListResellerInvoicesReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListResellerInvoicesOK), nil + +} diff --git a/services/billing/client/invoice_management/list_customer_invoices_parameters.go b/services/billing/client/invoice_management/list_customer_invoices_parameters.go new file mode 100644 index 0000000..17262dc --- /dev/null +++ b/services/billing/client/invoice_management/list_customer_invoices_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListCustomerInvoicesParams creates a new ListCustomerInvoicesParams object +// with the default values initialized. +func NewListCustomerInvoicesParams() *ListCustomerInvoicesParams { + + return &ListCustomerInvoicesParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListCustomerInvoicesParamsWithTimeout creates a new ListCustomerInvoicesParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListCustomerInvoicesParamsWithTimeout(timeout time.Duration) *ListCustomerInvoicesParams { + + return &ListCustomerInvoicesParams{ + + timeout: timeout, + } +} + +// NewListCustomerInvoicesParamsWithContext creates a new ListCustomerInvoicesParams object +// with the default values initialized, and the ability to set a context for a request +func NewListCustomerInvoicesParamsWithContext(ctx context.Context) *ListCustomerInvoicesParams { + + return &ListCustomerInvoicesParams{ + + Context: ctx, + } +} + +// NewListCustomerInvoicesParamsWithHTTPClient creates a new ListCustomerInvoicesParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListCustomerInvoicesParamsWithHTTPClient(client *http.Client) *ListCustomerInvoicesParams { + + return &ListCustomerInvoicesParams{ + HTTPClient: client, + } +} + +/*ListCustomerInvoicesParams contains all the parameters to send to the API endpoint +for the list customer invoices operation typically these are written to a http.Request +*/ +type ListCustomerInvoicesParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list customer invoices params +func (o *ListCustomerInvoicesParams) WithTimeout(timeout time.Duration) *ListCustomerInvoicesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list customer invoices params +func (o *ListCustomerInvoicesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list customer invoices params +func (o *ListCustomerInvoicesParams) WithContext(ctx context.Context) *ListCustomerInvoicesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list customer invoices params +func (o *ListCustomerInvoicesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list customer invoices params +func (o *ListCustomerInvoicesParams) WithHTTPClient(client *http.Client) *ListCustomerInvoicesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list customer invoices params +func (o *ListCustomerInvoicesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListCustomerInvoicesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/list_customer_invoices_responses.go b/services/billing/client/invoice_management/list_customer_invoices_responses.go new file mode 100644 index 0000000..c72712e --- /dev/null +++ b/services/billing/client/invoice_management/list_customer_invoices_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListCustomerInvoicesReader is a Reader for the ListCustomerInvoices structure. +type ListCustomerInvoicesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListCustomerInvoicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListCustomerInvoicesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListCustomerInvoicesInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListCustomerInvoicesOK creates a ListCustomerInvoicesOK with default headers values +func NewListCustomerInvoicesOK() *ListCustomerInvoicesOK { + return &ListCustomerInvoicesOK{} +} + +/*ListCustomerInvoicesOK handles this case with default header values. + +Description of a successfully operation +*/ +type ListCustomerInvoicesOK struct { + Payload []*models.Invoice +} + +func (o *ListCustomerInvoicesOK) Error() string { + return fmt.Sprintf("[GET /invoice/customer][%d] listCustomerInvoicesOK %+v", 200, o.Payload) +} + +func (o *ListCustomerInvoicesOK) GetPayload() []*models.Invoice { + return o.Payload +} + +func (o *ListCustomerInvoicesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListCustomerInvoicesInternalServerError creates a ListCustomerInvoicesInternalServerError with default headers values +func NewListCustomerInvoicesInternalServerError() *ListCustomerInvoicesInternalServerError { + return &ListCustomerInvoicesInternalServerError{} +} + +/*ListCustomerInvoicesInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListCustomerInvoicesInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListCustomerInvoicesInternalServerError) Error() string { + return fmt.Sprintf("[GET /invoice/customer][%d] listCustomerInvoicesInternalServerError %+v", 500, o.Payload) +} + +func (o *ListCustomerInvoicesInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListCustomerInvoicesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/list_invoices_parameters.go b/services/billing/client/invoice_management/list_invoices_parameters.go new file mode 100644 index 0000000..34536d9 --- /dev/null +++ b/services/billing/client/invoice_management/list_invoices_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// NewListInvoicesParams creates a new ListInvoicesParams object +// with the default values initialized. +func NewListInvoicesParams() *ListInvoicesParams { + var () + return &ListInvoicesParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListInvoicesParamsWithTimeout creates a new ListInvoicesParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListInvoicesParamsWithTimeout(timeout time.Duration) *ListInvoicesParams { + var () + return &ListInvoicesParams{ + + timeout: timeout, + } +} + +// NewListInvoicesParamsWithContext creates a new ListInvoicesParams object +// with the default values initialized, and the ability to set a context for a request +func NewListInvoicesParamsWithContext(ctx context.Context) *ListInvoicesParams { + var () + return &ListInvoicesParams{ + + Context: ctx, + } +} + +// NewListInvoicesParamsWithHTTPClient creates a new ListInvoicesParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListInvoicesParamsWithHTTPClient(client *http.Client) *ListInvoicesParams { + var () + return &ListInvoicesParams{ + HTTPClient: client, + } +} + +/*ListInvoicesParams contains all the parameters to send to the API endpoint +for the list invoices operation typically these are written to a http.Request +*/ +type ListInvoicesParams struct { + + /*Model + Invoice model partially filled to use for the filtering of the invoices + + */ + Model *models.Invoice + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list invoices params +func (o *ListInvoicesParams) WithTimeout(timeout time.Duration) *ListInvoicesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list invoices params +func (o *ListInvoicesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list invoices params +func (o *ListInvoicesParams) WithContext(ctx context.Context) *ListInvoicesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list invoices params +func (o *ListInvoicesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list invoices params +func (o *ListInvoicesParams) WithHTTPClient(client *http.Client) *ListInvoicesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list invoices params +func (o *ListInvoicesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithModel adds the model to the list invoices params +func (o *ListInvoicesParams) WithModel(model *models.Invoice) *ListInvoicesParams { + o.SetModel(model) + return o +} + +// SetModel adds the model to the list invoices params +func (o *ListInvoicesParams) SetModel(model *models.Invoice) { + o.Model = model +} + +// WriteToRequest writes these params to a swagger request +func (o *ListInvoicesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Model != nil { + if err := r.SetBodyParam(o.Model); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/list_invoices_responses.go b/services/billing/client/invoice_management/list_invoices_responses.go new file mode 100644 index 0000000..86afd7f --- /dev/null +++ b/services/billing/client/invoice_management/list_invoices_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListInvoicesReader is a Reader for the ListInvoices structure. +type ListInvoicesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListInvoicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListInvoicesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListInvoicesInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListInvoicesOK creates a ListInvoicesOK with default headers values +func NewListInvoicesOK() *ListInvoicesOK { + return &ListInvoicesOK{} +} + +/*ListInvoicesOK handles this case with default header values. + +Description of a successfully operation +*/ +type ListInvoicesOK struct { + Payload []*models.Invoice +} + +func (o *ListInvoicesOK) Error() string { + return fmt.Sprintf("[GET /invoice][%d] listInvoicesOK %+v", 200, o.Payload) +} + +func (o *ListInvoicesOK) GetPayload() []*models.Invoice { + return o.Payload +} + +func (o *ListInvoicesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListInvoicesInternalServerError creates a ListInvoicesInternalServerError with default headers values +func NewListInvoicesInternalServerError() *ListInvoicesInternalServerError { + return &ListInvoicesInternalServerError{} +} + +/*ListInvoicesInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListInvoicesInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListInvoicesInternalServerError) Error() string { + return fmt.Sprintf("[GET /invoice][%d] listInvoicesInternalServerError %+v", 500, o.Payload) +} + +func (o *ListInvoicesInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListInvoicesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/invoice_management/list_reseller_invoices_parameters.go b/services/billing/client/invoice_management/list_reseller_invoices_parameters.go new file mode 100644 index 0000000..2899b57 --- /dev/null +++ b/services/billing/client/invoice_management/list_reseller_invoices_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListResellerInvoicesParams creates a new ListResellerInvoicesParams object +// with the default values initialized. +func NewListResellerInvoicesParams() *ListResellerInvoicesParams { + + return &ListResellerInvoicesParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListResellerInvoicesParamsWithTimeout creates a new ListResellerInvoicesParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListResellerInvoicesParamsWithTimeout(timeout time.Duration) *ListResellerInvoicesParams { + + return &ListResellerInvoicesParams{ + + timeout: timeout, + } +} + +// NewListResellerInvoicesParamsWithContext creates a new ListResellerInvoicesParams object +// with the default values initialized, and the ability to set a context for a request +func NewListResellerInvoicesParamsWithContext(ctx context.Context) *ListResellerInvoicesParams { + + return &ListResellerInvoicesParams{ + + Context: ctx, + } +} + +// NewListResellerInvoicesParamsWithHTTPClient creates a new ListResellerInvoicesParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListResellerInvoicesParamsWithHTTPClient(client *http.Client) *ListResellerInvoicesParams { + + return &ListResellerInvoicesParams{ + HTTPClient: client, + } +} + +/*ListResellerInvoicesParams contains all the parameters to send to the API endpoint +for the list reseller invoices operation typically these are written to a http.Request +*/ +type ListResellerInvoicesParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list reseller invoices params +func (o *ListResellerInvoicesParams) WithTimeout(timeout time.Duration) *ListResellerInvoicesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list reseller invoices params +func (o *ListResellerInvoicesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list reseller invoices params +func (o *ListResellerInvoicesParams) WithContext(ctx context.Context) *ListResellerInvoicesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list reseller invoices params +func (o *ListResellerInvoicesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list reseller invoices params +func (o *ListResellerInvoicesParams) WithHTTPClient(client *http.Client) *ListResellerInvoicesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list reseller invoices params +func (o *ListResellerInvoicesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListResellerInvoicesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/invoice_management/list_reseller_invoices_responses.go b/services/billing/client/invoice_management/list_reseller_invoices_responses.go new file mode 100644 index 0000000..f069224 --- /dev/null +++ b/services/billing/client/invoice_management/list_reseller_invoices_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListResellerInvoicesReader is a Reader for the ListResellerInvoices structure. +type ListResellerInvoicesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListResellerInvoicesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListResellerInvoicesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListResellerInvoicesInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListResellerInvoicesOK creates a ListResellerInvoicesOK with default headers values +func NewListResellerInvoicesOK() *ListResellerInvoicesOK { + return &ListResellerInvoicesOK{} +} + +/*ListResellerInvoicesOK handles this case with default header values. + +Description of a successfully operation +*/ +type ListResellerInvoicesOK struct { + Payload []*models.Invoice +} + +func (o *ListResellerInvoicesOK) Error() string { + return fmt.Sprintf("[GET /invoice/reseller][%d] listResellerInvoicesOK %+v", 200, o.Payload) +} + +func (o *ListResellerInvoicesOK) GetPayload() []*models.Invoice { + return o.Payload +} + +func (o *ListResellerInvoicesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListResellerInvoicesInternalServerError creates a ListResellerInvoicesInternalServerError with default headers values +func NewListResellerInvoicesInternalServerError() *ListResellerInvoicesInternalServerError { + return &ListResellerInvoicesInternalServerError{} +} + +/*ListResellerInvoicesInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListResellerInvoicesInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListResellerInvoicesInternalServerError) Error() string { + return fmt.Sprintf("[GET /invoice/reseller][%d] listResellerInvoicesInternalServerError %+v", 500, o.Payload) +} + +func (o *ListResellerInvoicesInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListResellerInvoicesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/status_management/get_status_parameters.go b/services/billing/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..bc38256 --- /dev/null +++ b/services/billing/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the endpoint to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/status_management/get_status_responses.go b/services/billing/client/status_management/get_status_responses.go new file mode 100644 index 0000000..2bcd8f8 --- /dev/null +++ b/services/billing/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/status_management/show_status_parameters.go b/services/billing/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/services/billing/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/status_management/show_status_responses.go b/services/billing/client/status_management/show_status_responses.go new file mode 100644 index 0000000..4902e74 --- /dev/null +++ b/services/billing/client/status_management/show_status_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/status_management/status_management_client.go b/services/billing/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/services/billing/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/services/billing/client/trigger_management/periodic_run_parameters.go b/services/billing/client/trigger_management/periodic_run_parameters.go new file mode 100644 index 0000000..43b91b4 --- /dev/null +++ b/services/billing/client/trigger_management/periodic_run_parameters.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPeriodicRunParams creates a new PeriodicRunParams object +// with the default values initialized. +func NewPeriodicRunParams() *PeriodicRunParams { + var () + return &PeriodicRunParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewPeriodicRunParamsWithTimeout creates a new PeriodicRunParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewPeriodicRunParamsWithTimeout(timeout time.Duration) *PeriodicRunParams { + var () + return &PeriodicRunParams{ + + timeout: timeout, + } +} + +// NewPeriodicRunParamsWithContext creates a new PeriodicRunParams object +// with the default values initialized, and the ability to set a context for a request +func NewPeriodicRunParamsWithContext(ctx context.Context) *PeriodicRunParams { + var () + return &PeriodicRunParams{ + + Context: ctx, + } +} + +// NewPeriodicRunParamsWithHTTPClient creates a new PeriodicRunParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewPeriodicRunParamsWithHTTPClient(client *http.Client) *PeriodicRunParams { + var () + return &PeriodicRunParams{ + HTTPClient: client, + } +} + +/*PeriodicRunParams contains all the parameters to send to the API endpoint +for the periodic run operation typically these are written to a http.Request +*/ +type PeriodicRunParams struct { + + /*Today + Datetime to override the time.now() to simulate other days + + */ + Today *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the periodic run params +func (o *PeriodicRunParams) WithTimeout(timeout time.Duration) *PeriodicRunParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the periodic run params +func (o *PeriodicRunParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the periodic run params +func (o *PeriodicRunParams) WithContext(ctx context.Context) *PeriodicRunParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the periodic run params +func (o *PeriodicRunParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the periodic run params +func (o *PeriodicRunParams) WithHTTPClient(client *http.Client) *PeriodicRunParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the periodic run params +func (o *PeriodicRunParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithToday adds the today to the periodic run params +func (o *PeriodicRunParams) WithToday(today *strfmt.DateTime) *PeriodicRunParams { + o.SetToday(today) + return o +} + +// SetToday adds the today to the periodic run params +func (o *PeriodicRunParams) SetToday(today *strfmt.DateTime) { + o.Today = today +} + +// WriteToRequest writes these params to a swagger request +func (o *PeriodicRunParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Today != nil { + + // query param today + var qrToday strfmt.DateTime + if o.Today != nil { + qrToday = *o.Today + } + qToday := qrToday.String() + if qToday != "" { + if err := r.SetQueryParam("today", qToday); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/client/trigger_management/periodic_run_responses.go b/services/billing/client/trigger_management/periodic_run_responses.go new file mode 100644 index 0000000..c79806d --- /dev/null +++ b/services/billing/client/trigger_management/periodic_run_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// PeriodicRunReader is a Reader for the PeriodicRun structure. +type PeriodicRunReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PeriodicRunReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 202: + result := NewPeriodicRunAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewPeriodicRunAccepted creates a PeriodicRunAccepted with default headers values +func NewPeriodicRunAccepted() *PeriodicRunAccepted { + return &PeriodicRunAccepted{} +} + +/*PeriodicRunAccepted handles this case with default header values. + +The request for processing the periodic run had been added to the queue +*/ +type PeriodicRunAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *PeriodicRunAccepted) Error() string { + return fmt.Sprintf("[GET /trigger/periodicrun][%d] periodicRunAccepted %+v", 202, o.Payload) +} + +func (o *PeriodicRunAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *PeriodicRunAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/billing/client/trigger_management/trigger_management_client.go b/services/billing/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..ad0c330 --- /dev/null +++ b/services/billing/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + PeriodicRun periodics run of the bulk generation of invoices*/ + PeriodicRun(ctx context.Context, params *PeriodicRunParams) (*PeriodicRunAccepted, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +PeriodicRun periodics run of the bulk generation of invoices +*/ +func (a *Client) PeriodicRun(ctx context.Context, params *PeriodicRunParams) (*PeriodicRunAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "periodicRun", + Method: "GET", + PathPattern: "/trigger/periodicrun", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &PeriodicRunReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*PeriodicRunAccepted), nil + +} diff --git a/services/billing/go.mod b/services/billing/go.mod new file mode 100644 index 0000000..12e326f --- /dev/null +++ b/services/billing/go.mod @@ -0,0 +1,25 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing + +go 1.15 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/lib/pq v1.10.4 + github.com/prometheus/client_golang v1.11.0 + github.com/rs/cors v1.8.2 + github.com/spf13/viper v1.10.1 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/services/billing/models/bill_run.go b/services/billing/models/bill_run.go new file mode 100644 index 0000000..918444c --- /dev/null +++ b/services/billing/models/bill_run.go @@ -0,0 +1,203 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "github.com/lib/pq" +) + +// BillRun bill run +// +// swagger:model BillRun +type BillRun struct { + + // amount invoiced + AmountInvoiced float64 `json:"AmountInvoiced,omitempty" gorm:"type:numeric(23,13)"` + + // creation timestamp + // Format: date-time + CreationTimestamp strfmt.DateTime `json:"CreationTimestamp,omitempty" gorm:"type:timestamptz"` + + // execution type + ExecutionType string `json:"ExecutionType,omitempty"` + + // ID + // Format: uuid + ID strfmt.UUID `json:"ID,omitempty" gorm:"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // invoices count + InvoicesCount int64 `json:"InvoicesCount,omitempty"` + + // invoices error count + InvoicesErrorCount int64 `json:"InvoicesErrorCount,omitempty"` + + // invoices error list + InvoicesErrorList pq.StringArray `json:"InvoicesErrorList,omitempty" gorm:"type:text[]"` + + // invoices list + InvoicesList []*InvoiceMetadata `json:"InvoicesList" gorm:"-"` + + // invoices processed count + InvoicesProcessedCount int64 `json:"InvoicesProcessedCount,omitempty"` + + // organizations involved + OrganizationsInvolved pq.StringArray `json:"OrganizationsInvolved,omitempty" gorm:"type:text[]"` + + // status + // Enum: [ERROR FINISHED PROCESSING QUEUED] + Status *string `json:"Status,omitempty" gorm:"default:QUEUED"` +} + +// Validate validates this bill run +func (m *BillRun) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreationTimestamp(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInvoicesList(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *BillRun) validateCreationTimestamp(formats strfmt.Registry) error { + + if swag.IsZero(m.CreationTimestamp) { // not required + return nil + } + + if err := validate.FormatOf("CreationTimestamp", "body", "date-time", m.CreationTimestamp.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *BillRun) validateID(formats strfmt.Registry) error { + + if swag.IsZero(m.ID) { // not required + return nil + } + + if err := validate.FormatOf("ID", "body", "uuid", m.ID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *BillRun) validateInvoicesList(formats strfmt.Registry) error { + + if swag.IsZero(m.InvoicesList) { // not required + return nil + } + + for i := 0; i < len(m.InvoicesList); i++ { + if swag.IsZero(m.InvoicesList[i]) { // not required + continue + } + + if m.InvoicesList[i] != nil { + if err := m.InvoicesList[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("InvoicesList" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +var billRunTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ERROR","FINISHED","PROCESSING","QUEUED"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + billRunTypeStatusPropEnum = append(billRunTypeStatusPropEnum, v) + } +} + +const ( + + // BillRunStatusERROR captures enum value "ERROR" + BillRunStatusERROR string = "ERROR" + + // BillRunStatusFINISHED captures enum value "FINISHED" + BillRunStatusFINISHED string = "FINISHED" + + // BillRunStatusPROCESSING captures enum value "PROCESSING" + BillRunStatusPROCESSING string = "PROCESSING" + + // BillRunStatusQUEUED captures enum value "QUEUED" + BillRunStatusQUEUED string = "QUEUED" +) + +// prop value enum +func (m *BillRun) validateStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, billRunTypeStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *BillRun) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("Status", "body", *m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *BillRun) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *BillRun) UnmarshalBinary(b []byte) error { + var res BillRun + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/models/bill_run_list.go b/services/billing/models/bill_run_list.go new file mode 100644 index 0000000..dd2b541 --- /dev/null +++ b/services/billing/models/bill_run_list.go @@ -0,0 +1,167 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "github.com/lib/pq" +) + +// BillRunList bill run list +// +// swagger:model BillRunList +type BillRunList struct { + + // amount invoiced + AmountInvoiced float64 `json:"AmountInvoiced,omitempty"` + + // creation timestamp + // Format: date-time + CreationTimestamp strfmt.DateTime `json:"CreationTimestamp,omitempty"` + + // ID + // Format: uuid + ID strfmt.UUID `json:"ID,omitempty"` + + // invoices count + InvoicesCount int64 `json:"InvoicesCount,omitempty"` + + // invoices error count + InvoicesErrorCount int64 `json:"InvoicesErrorCount,omitempty"` + + // invoices error list + InvoicesErrorList pq.StringArray `json:"InvoicesErrorList,omitempty" gorm:"type:text[]"` + + // invoices processed count + InvoicesProcessedCount int64 `json:"InvoicesProcessedCount,omitempty"` + + // organizations involved + OrganizationsInvolved pq.StringArray `json:"OrganizationsInvolved,omitempty" gorm:"type:text[]"` + + // status + // Enum: [ERROR FINISHED PROCESSING QUEUED] + Status *string `json:"Status,omitempty"` +} + +// Validate validates this bill run list +func (m *BillRunList) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreationTimestamp(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *BillRunList) validateCreationTimestamp(formats strfmt.Registry) error { + + if swag.IsZero(m.CreationTimestamp) { // not required + return nil + } + + if err := validate.FormatOf("CreationTimestamp", "body", "date-time", m.CreationTimestamp.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *BillRunList) validateID(formats strfmt.Registry) error { + + if swag.IsZero(m.ID) { // not required + return nil + } + + if err := validate.FormatOf("ID", "body", "uuid", m.ID.String(), formats); err != nil { + return err + } + + return nil +} + +var billRunListTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ERROR","FINISHED","PROCESSING","QUEUED"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + billRunListTypeStatusPropEnum = append(billRunListTypeStatusPropEnum, v) + } +} + +const ( + + // BillRunListStatusERROR captures enum value "ERROR" + BillRunListStatusERROR string = "ERROR" + + // BillRunListStatusFINISHED captures enum value "FINISHED" + BillRunListStatusFINISHED string = "FINISHED" + + // BillRunListStatusPROCESSING captures enum value "PROCESSING" + BillRunListStatusPROCESSING string = "PROCESSING" + + // BillRunListStatusQUEUED captures enum value "QUEUED" + BillRunListStatusQUEUED string = "QUEUED" +) + +// prop value enum +func (m *BillRunList) validateStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, billRunListTypeStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *BillRunList) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("Status", "body", *m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *BillRunList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *BillRunList) UnmarshalBinary(b []byte) error { + var res BillRunList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/models/bill_run_report.go b/services/billing/models/bill_run_report.go new file mode 100644 index 0000000..f4ebb00 --- /dev/null +++ b/services/billing/models/bill_run_report.go @@ -0,0 +1,197 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "github.com/lib/pq" +) + +// BillRunReport bill run report +// +// swagger:model BillRunReport +type BillRunReport struct { + + // amount invoiced + AmountInvoiced float64 `json:"AmountInvoiced,omitempty"` + + // creation timestamp + // Format: date-time + CreationTimestamp strfmt.DateTime `json:"CreationTimestamp,omitempty"` + + // ID + // Format: uuid + ID strfmt.UUID `json:"ID,omitempty"` + + // invoices count + InvoicesCount int64 `json:"InvoicesCount,omitempty"` + + // invoices error count + InvoicesErrorCount int64 `json:"InvoicesErrorCount,omitempty"` + + // invoices error list + InvoicesErrorList pq.StringArray `json:"InvoicesErrorList,omitempty" gorm:"type:text[]"` + + // invoices list + InvoicesList []*InvoiceMetadata `json:"InvoicesList" gorm:"-"` + + // invoices processed count + InvoicesProcessedCount int64 `json:"InvoicesProcessedCount,omitempty"` + + // status + // Enum: [ERROR FINISHED PROCESSING QUEUED] + Status *string `json:"Status,omitempty"` +} + +// Validate validates this bill run report +func (m *BillRunReport) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreationTimestamp(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInvoicesList(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *BillRunReport) validateCreationTimestamp(formats strfmt.Registry) error { + + if swag.IsZero(m.CreationTimestamp) { // not required + return nil + } + + if err := validate.FormatOf("CreationTimestamp", "body", "date-time", m.CreationTimestamp.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *BillRunReport) validateID(formats strfmt.Registry) error { + + if swag.IsZero(m.ID) { // not required + return nil + } + + if err := validate.FormatOf("ID", "body", "uuid", m.ID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *BillRunReport) validateInvoicesList(formats strfmt.Registry) error { + + if swag.IsZero(m.InvoicesList) { // not required + return nil + } + + for i := 0; i < len(m.InvoicesList); i++ { + if swag.IsZero(m.InvoicesList[i]) { // not required + continue + } + + if m.InvoicesList[i] != nil { + if err := m.InvoicesList[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("InvoicesList" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +var billRunReportTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ERROR","FINISHED","PROCESSING","QUEUED"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + billRunReportTypeStatusPropEnum = append(billRunReportTypeStatusPropEnum, v) + } +} + +const ( + + // BillRunReportStatusERROR captures enum value "ERROR" + BillRunReportStatusERROR string = "ERROR" + + // BillRunReportStatusFINISHED captures enum value "FINISHED" + BillRunReportStatusFINISHED string = "FINISHED" + + // BillRunReportStatusPROCESSING captures enum value "PROCESSING" + BillRunReportStatusPROCESSING string = "PROCESSING" + + // BillRunReportStatusQUEUED captures enum value "QUEUED" + BillRunReportStatusQUEUED string = "QUEUED" +) + +// prop value enum +func (m *BillRunReport) validateStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, billRunReportTypeStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *BillRunReport) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("Status", "body", *m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *BillRunReport) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *BillRunReport) UnmarshalBinary(b []byte) error { + var res BillRunReport + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/models/error_response.go b/services/billing/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/services/billing/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/models/invoice.go b/services/billing/models/invoice.go new file mode 100644 index 0000000..0ee71d1 --- /dev/null +++ b/services/billing/models/invoice.go @@ -0,0 +1,359 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// Invoice invoice +// +// swagger:model Invoice +type Invoice struct { + + // amount invoiced + AmountInvoiced float64 `json:"AmountInvoiced,omitempty" gorm:"type:numeric(23,13)"` + + // bill run ID + // Format: uuid + BillRunID strfmt.UUID `json:"BillRunID,omitempty"` + + // billing contact + BillingContact string `json:"BillingContact,omitempty"` + + // currency + // Enum: [CHF EUR USD] + Currency *string `json:"Currency,omitempty"` + + // generation timestamp + // Format: date-time + GenerationTimestamp strfmt.DateTime `json:"GenerationTimestamp,omitempty" gorm:"type:timestamptz"` + + // ID + // Format: uuid + ID strfmt.UUID `json:"ID,omitempty" gorm:"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // items + Items datamodels.JSONdb `json:"Items,omitempty" gorm:"type:jsonb"` + + // organization ID + OrganizationID string `json:"OrganizationID,omitempty"` + + // organization name + OrganizationName string `json:"OrganizationName,omitempty"` + + // organization type + OrganizationType string `json:"OrganizationType,omitempty"` + + // payment deadline + // Format: date + PaymentDeadline strfmt.Date `json:"PaymentDeadline,omitempty" gorm:"type:date"` + + // payment status + // Enum: [CANCELLED PAID UNPAID] + PaymentStatus *string `json:"PaymentStatus,omitempty"` + + // period end date + // Format: date + PeriodEndDate strfmt.Date `json:"PeriodEndDate,omitempty" gorm:"type:date"` + + // period start date + // Format: date + PeriodStartDate strfmt.Date `json:"PeriodStartDate,omitempty" gorm:"type:date"` + + // status + // Enum: [ERROR FINISHED NOT_PROCESSED PROCESSING] + Status *string `json:"Status,omitempty" gorm:"default:NOT_PROCESSED"` +} + +// Validate validates this invoice +func (m *Invoice) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBillRunID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCurrency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGenerationTimestamp(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymentDeadline(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymentStatus(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePeriodEndDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePeriodStartDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Invoice) validateBillRunID(formats strfmt.Registry) error { + + if swag.IsZero(m.BillRunID) { // not required + return nil + } + + if err := validate.FormatOf("BillRunID", "body", "uuid", m.BillRunID.String(), formats); err != nil { + return err + } + + return nil +} + +var invoiceTypeCurrencyPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CHF","EUR","USD"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + invoiceTypeCurrencyPropEnum = append(invoiceTypeCurrencyPropEnum, v) + } +} + +const ( + + // InvoiceCurrencyCHF captures enum value "CHF" + InvoiceCurrencyCHF string = "CHF" + + // InvoiceCurrencyEUR captures enum value "EUR" + InvoiceCurrencyEUR string = "EUR" + + // InvoiceCurrencyUSD captures enum value "USD" + InvoiceCurrencyUSD string = "USD" +) + +// prop value enum +func (m *Invoice) validateCurrencyEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, invoiceTypeCurrencyPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Invoice) validateCurrency(formats strfmt.Registry) error { + + if swag.IsZero(m.Currency) { // not required + return nil + } + + // value enum + if err := m.validateCurrencyEnum("Currency", "body", *m.Currency); err != nil { + return err + } + + return nil +} + +func (m *Invoice) validateGenerationTimestamp(formats strfmt.Registry) error { + + if swag.IsZero(m.GenerationTimestamp) { // not required + return nil + } + + if err := validate.FormatOf("GenerationTimestamp", "body", "date-time", m.GenerationTimestamp.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Invoice) validateID(formats strfmt.Registry) error { + + if swag.IsZero(m.ID) { // not required + return nil + } + + if err := validate.FormatOf("ID", "body", "uuid", m.ID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Invoice) validatePaymentDeadline(formats strfmt.Registry) error { + + if swag.IsZero(m.PaymentDeadline) { // not required + return nil + } + + if err := validate.FormatOf("PaymentDeadline", "body", "date", m.PaymentDeadline.String(), formats); err != nil { + return err + } + + return nil +} + +var invoiceTypePaymentStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CANCELLED","PAID","UNPAID"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + invoiceTypePaymentStatusPropEnum = append(invoiceTypePaymentStatusPropEnum, v) + } +} + +const ( + + // InvoicePaymentStatusCANCELLED captures enum value "CANCELLED" + InvoicePaymentStatusCANCELLED string = "CANCELLED" + + // InvoicePaymentStatusPAID captures enum value "PAID" + InvoicePaymentStatusPAID string = "PAID" + + // InvoicePaymentStatusUNPAID captures enum value "UNPAID" + InvoicePaymentStatusUNPAID string = "UNPAID" +) + +// prop value enum +func (m *Invoice) validatePaymentStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, invoiceTypePaymentStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Invoice) validatePaymentStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.PaymentStatus) { // not required + return nil + } + + // value enum + if err := m.validatePaymentStatusEnum("PaymentStatus", "body", *m.PaymentStatus); err != nil { + return err + } + + return nil +} + +func (m *Invoice) validatePeriodEndDate(formats strfmt.Registry) error { + + if swag.IsZero(m.PeriodEndDate) { // not required + return nil + } + + if err := validate.FormatOf("PeriodEndDate", "body", "date", m.PeriodEndDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Invoice) validatePeriodStartDate(formats strfmt.Registry) error { + + if swag.IsZero(m.PeriodStartDate) { // not required + return nil + } + + if err := validate.FormatOf("PeriodStartDate", "body", "date", m.PeriodStartDate.String(), formats); err != nil { + return err + } + + return nil +} + +var invoiceTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ERROR","FINISHED","NOT_PROCESSED","PROCESSING"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + invoiceTypeStatusPropEnum = append(invoiceTypeStatusPropEnum, v) + } +} + +const ( + + // InvoiceStatusERROR captures enum value "ERROR" + InvoiceStatusERROR string = "ERROR" + + // InvoiceStatusFINISHED captures enum value "FINISHED" + InvoiceStatusFINISHED string = "FINISHED" + + // InvoiceStatusNOTPROCESSED captures enum value "NOT_PROCESSED" + InvoiceStatusNOTPROCESSED string = "NOT_PROCESSED" + + // InvoiceStatusPROCESSING captures enum value "PROCESSING" + InvoiceStatusPROCESSING string = "PROCESSING" +) + +// prop value enum +func (m *Invoice) validateStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, invoiceTypeStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Invoice) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("Status", "body", *m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Invoice) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Invoice) UnmarshalBinary(b []byte) error { + var res Invoice + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/models/invoice_metadata.go b/services/billing/models/invoice_metadata.go new file mode 100644 index 0000000..b976a50 --- /dev/null +++ b/services/billing/models/invoice_metadata.go @@ -0,0 +1,307 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// InvoiceMetadata invoice metadata +// +// swagger:model InvoiceMetadata +type InvoiceMetadata struct { + + // amount invoiced + AmountInvoiced float64 `json:"AmountInvoiced,omitempty"` + + // currency + // Enum: [CHF EUR USD] + Currency *string `json:"Currency,omitempty"` + + // ID + // Format: uuid + ID strfmt.UUID `json:"ID,omitempty"` + + // organization ID + OrganizationID string `json:"OrganizationID,omitempty"` + + // organization name + OrganizationName string `json:"OrganizationName,omitempty"` + + // payment deadline + // Format: date + PaymentDeadline strfmt.Date `json:"PaymentDeadline,omitempty"` + + // payment status + // Enum: [CANCELLED PAID UNPAID] + PaymentStatus *string `json:"PaymentStatus,omitempty"` + + // period end date + // Format: date + PeriodEndDate strfmt.Date `json:"PeriodEndDate,omitempty"` + + // period start date + // Format: date + PeriodStartDate strfmt.Date `json:"PeriodStartDate,omitempty"` + + // status + // Enum: [ERROR FINISHED NOT_PROCESSED PROCESSING] + Status *string `json:"Status,omitempty"` +} + +// Validate validates this invoice metadata +func (m *InvoiceMetadata) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCurrency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateID(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymentDeadline(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePaymentStatus(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePeriodEndDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePeriodStartDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var invoiceMetadataTypeCurrencyPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CHF","EUR","USD"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + invoiceMetadataTypeCurrencyPropEnum = append(invoiceMetadataTypeCurrencyPropEnum, v) + } +} + +const ( + + // InvoiceMetadataCurrencyCHF captures enum value "CHF" + InvoiceMetadataCurrencyCHF string = "CHF" + + // InvoiceMetadataCurrencyEUR captures enum value "EUR" + InvoiceMetadataCurrencyEUR string = "EUR" + + // InvoiceMetadataCurrencyUSD captures enum value "USD" + InvoiceMetadataCurrencyUSD string = "USD" +) + +// prop value enum +func (m *InvoiceMetadata) validateCurrencyEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, invoiceMetadataTypeCurrencyPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *InvoiceMetadata) validateCurrency(formats strfmt.Registry) error { + + if swag.IsZero(m.Currency) { // not required + return nil + } + + // value enum + if err := m.validateCurrencyEnum("Currency", "body", *m.Currency); err != nil { + return err + } + + return nil +} + +func (m *InvoiceMetadata) validateID(formats strfmt.Registry) error { + + if swag.IsZero(m.ID) { // not required + return nil + } + + if err := validate.FormatOf("ID", "body", "uuid", m.ID.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *InvoiceMetadata) validatePaymentDeadline(formats strfmt.Registry) error { + + if swag.IsZero(m.PaymentDeadline) { // not required + return nil + } + + if err := validate.FormatOf("PaymentDeadline", "body", "date", m.PaymentDeadline.String(), formats); err != nil { + return err + } + + return nil +} + +var invoiceMetadataTypePaymentStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CANCELLED","PAID","UNPAID"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + invoiceMetadataTypePaymentStatusPropEnum = append(invoiceMetadataTypePaymentStatusPropEnum, v) + } +} + +const ( + + // InvoiceMetadataPaymentStatusCANCELLED captures enum value "CANCELLED" + InvoiceMetadataPaymentStatusCANCELLED string = "CANCELLED" + + // InvoiceMetadataPaymentStatusPAID captures enum value "PAID" + InvoiceMetadataPaymentStatusPAID string = "PAID" + + // InvoiceMetadataPaymentStatusUNPAID captures enum value "UNPAID" + InvoiceMetadataPaymentStatusUNPAID string = "UNPAID" +) + +// prop value enum +func (m *InvoiceMetadata) validatePaymentStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, invoiceMetadataTypePaymentStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *InvoiceMetadata) validatePaymentStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.PaymentStatus) { // not required + return nil + } + + // value enum + if err := m.validatePaymentStatusEnum("PaymentStatus", "body", *m.PaymentStatus); err != nil { + return err + } + + return nil +} + +func (m *InvoiceMetadata) validatePeriodEndDate(formats strfmt.Registry) error { + + if swag.IsZero(m.PeriodEndDate) { // not required + return nil + } + + if err := validate.FormatOf("PeriodEndDate", "body", "date", m.PeriodEndDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *InvoiceMetadata) validatePeriodStartDate(formats strfmt.Registry) error { + + if swag.IsZero(m.PeriodStartDate) { // not required + return nil + } + + if err := validate.FormatOf("PeriodStartDate", "body", "date", m.PeriodStartDate.String(), formats); err != nil { + return err + } + + return nil +} + +var invoiceMetadataTypeStatusPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["ERROR","FINISHED","NOT_PROCESSED","PROCESSING"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + invoiceMetadataTypeStatusPropEnum = append(invoiceMetadataTypeStatusPropEnum, v) + } +} + +const ( + + // InvoiceMetadataStatusERROR captures enum value "ERROR" + InvoiceMetadataStatusERROR string = "ERROR" + + // InvoiceMetadataStatusFINISHED captures enum value "FINISHED" + InvoiceMetadataStatusFINISHED string = "FINISHED" + + // InvoiceMetadataStatusNOTPROCESSED captures enum value "NOT_PROCESSED" + InvoiceMetadataStatusNOTPROCESSED string = "NOT_PROCESSED" + + // InvoiceMetadataStatusPROCESSING captures enum value "PROCESSING" + InvoiceMetadataStatusPROCESSING string = "PROCESSING" +) + +// prop value enum +func (m *InvoiceMetadata) validateStatusEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, invoiceMetadataTypeStatusPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *InvoiceMetadata) validateStatus(formats strfmt.Registry) error { + + if swag.IsZero(m.Status) { // not required + return nil + } + + // value enum + if err := m.validateStatusEnum("Status", "body", *m.Status); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *InvoiceMetadata) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *InvoiceMetadata) UnmarshalBinary(b []byte) error { + var res InvoiceMetadata + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/models/item_created_response.go b/services/billing/models/item_created_response.go new file mode 100644 index 0000000..ea34934 --- /dev/null +++ b/services/billing/models/item_created_response.go @@ -0,0 +1,46 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ItemCreatedResponse item created response +// +// swagger:model ItemCreatedResponse +type ItemCreatedResponse struct { + + // Api link + APILink string `json:"ApiLink,omitempty"` + + // message + Message string `json:"Message,omitempty"` +} + +// Validate validates this item created response +func (m *ItemCreatedResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ItemCreatedResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ItemCreatedResponse) UnmarshalBinary(b []byte) error { + var res ItemCreatedResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/models/status.go b/services/billing/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/services/billing/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/billing/restapi/configure_billing_management_api.go b/services/billing/restapi/configure_billing_management_api.go new file mode 100644 index 0000000..e1dc7eb --- /dev/null +++ b/services/billing/restapi/configure_billing_management_api.go @@ -0,0 +1,283 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/bulk_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/invoice_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/trigger_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name BulkManagementAPI -inpkg + +/* BulkManagementAPI */ +type BulkManagementAPI interface { + /* GetBillRun Get the status report of the billrun requested */ + GetBillRun(ctx context.Context, params bulk_management.GetBillRunParams) middleware.Responder + + /* ListBillRuns Show the status report of the billruns present in the system */ + ListBillRuns(ctx context.Context, params bulk_management.ListBillRunsParams) middleware.Responder + + /* ListBillRunsByOrganization Show the status report of the billruns present in the system */ + ListBillRunsByOrganization(ctx context.Context, params bulk_management.ListBillRunsByOrganizationParams) middleware.Responder + + /* ReRunAllBillRuns Try to re-run the failed invoices in all the billruns. */ + ReRunAllBillRuns(ctx context.Context, params bulk_management.ReRunAllBillRunsParams) middleware.Responder + + /* ReRunBillRun Try to re-run the failed invoices in the billrun. */ + ReRunBillRun(ctx context.Context, params bulk_management.ReRunBillRunParams) middleware.Responder +} + +//go:generate mockery -name InvoiceManagementAPI -inpkg + +/* InvoiceManagementAPI */ +type InvoiceManagementAPI interface { + /* GenerateInvoiceForCustomer Generate invoice for the provided customer for the provided time window or last period */ + GenerateInvoiceForCustomer(ctx context.Context, params invoice_management.GenerateInvoiceForCustomerParams) middleware.Responder + + /* GenerateInvoiceForReseller Generate invoice for the provided reseller for the provided time window or last period */ + GenerateInvoiceForReseller(ctx context.Context, params invoice_management.GenerateInvoiceForResellerParams) middleware.Responder + + /* GetInvoice Summary for this endpoint */ + GetInvoice(ctx context.Context, params invoice_management.GetInvoiceParams) middleware.Responder + + /* GetInvoicesByCustomer Retrieve invoices by customer id */ + GetInvoicesByCustomer(ctx context.Context, params invoice_management.GetInvoicesByCustomerParams) middleware.Responder + + /* GetInvoicesByReseller Retrieve invoices by reseller id */ + GetInvoicesByReseller(ctx context.Context, params invoice_management.GetInvoicesByResellerParams) middleware.Responder + + /* ListCustomerInvoices Retrieve customers' invoices */ + ListCustomerInvoices(ctx context.Context, params invoice_management.ListCustomerInvoicesParams) middleware.Responder + + /* ListInvoices Summary for this endpoint */ + ListInvoices(ctx context.Context, params invoice_management.ListInvoicesParams) middleware.Responder + + /* ListResellerInvoices Retrieve resellers' invoices */ + ListResellerInvoices(ctx context.Context, params invoice_management.ListResellerInvoicesParams) middleware.Responder +} + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* PeriodicRun Periodic run of the bulk generation of invoices */ + PeriodicRun(ctx context.Context, params trigger_management.PeriodicRunParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + BulkManagementAPI + InvoiceManagementAPI + StatusManagementAPI + TriggerManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) + // Authenticator to use for all APIKey authentication + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // Authenticator to use for all Bearer authentication + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // Authenticator to use for all Basic authentication + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *BillingManagementAPI instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.BillingManagementAPIAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewBillingManagementAPIAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + if c.APIKeyAuthenticator != nil { + api.APIKeyAuthenticator = c.APIKeyAuthenticator + } + if c.BasicAuthenticator != nil { + api.BasicAuthenticator = c.BasicAuthenticator + } + if c.BearerAuthenticator != nil { + api.BearerAuthenticator = c.BearerAuthenticator + } + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.InvoiceManagementGenerateInvoiceForCustomerHandler = invoice_management.GenerateInvoiceForCustomerHandlerFunc(func(params invoice_management.GenerateInvoiceForCustomerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.GenerateInvoiceForCustomer(ctx, params) + }) + api.InvoiceManagementGenerateInvoiceForResellerHandler = invoice_management.GenerateInvoiceForResellerHandlerFunc(func(params invoice_management.GenerateInvoiceForResellerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.GenerateInvoiceForReseller(ctx, params) + }) + api.BulkManagementGetBillRunHandler = bulk_management.GetBillRunHandlerFunc(func(params bulk_management.GetBillRunParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BulkManagementAPI.GetBillRun(ctx, params) + }) + api.InvoiceManagementGetInvoiceHandler = invoice_management.GetInvoiceHandlerFunc(func(params invoice_management.GetInvoiceParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.GetInvoice(ctx, params) + }) + api.InvoiceManagementGetInvoicesByCustomerHandler = invoice_management.GetInvoicesByCustomerHandlerFunc(func(params invoice_management.GetInvoicesByCustomerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.GetInvoicesByCustomer(ctx, params) + }) + api.InvoiceManagementGetInvoicesByResellerHandler = invoice_management.GetInvoicesByResellerHandlerFunc(func(params invoice_management.GetInvoicesByResellerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.GetInvoicesByReseller(ctx, params) + }) + api.BulkManagementListBillRunsHandler = bulk_management.ListBillRunsHandlerFunc(func(params bulk_management.ListBillRunsParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BulkManagementAPI.ListBillRuns(ctx, params) + }) + api.BulkManagementListBillRunsByOrganizationHandler = bulk_management.ListBillRunsByOrganizationHandlerFunc(func(params bulk_management.ListBillRunsByOrganizationParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BulkManagementAPI.ListBillRunsByOrganization(ctx, params) + }) + api.InvoiceManagementListCustomerInvoicesHandler = invoice_management.ListCustomerInvoicesHandlerFunc(func(params invoice_management.ListCustomerInvoicesParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.ListCustomerInvoices(ctx, params) + }) + api.InvoiceManagementListInvoicesHandler = invoice_management.ListInvoicesHandlerFunc(func(params invoice_management.ListInvoicesParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.ListInvoices(ctx, params) + }) + api.InvoiceManagementListResellerInvoicesHandler = invoice_management.ListResellerInvoicesHandlerFunc(func(params invoice_management.ListResellerInvoicesParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.InvoiceManagementAPI.ListResellerInvoices(ctx, params) + }) + api.BulkManagementReRunAllBillRunsHandler = bulk_management.ReRunAllBillRunsHandlerFunc(func(params bulk_management.ReRunAllBillRunsParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BulkManagementAPI.ReRunAllBillRuns(ctx, params) + }) + api.BulkManagementReRunBillRunHandler = bulk_management.ReRunBillRunHandlerFunc(func(params bulk_management.ReRunBillRunParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BulkManagementAPI.ReRunBillRun(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.TriggerManagementPeriodicRunHandler = trigger_management.PeriodicRunHandlerFunc(func(params trigger_management.PeriodicRunParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.PeriodicRun(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/services/billing/restapi/doc.go b/services/billing/restapi/doc.go new file mode 100644 index 0000000..1f19464 --- /dev/null +++ b/services/billing/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi Billing Management API +// +// An API which supports creation, deletion, listing etc of Billing +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v1.0 +// Version: 1.0.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/services/billing/restapi/embedded_spec.go b/services/billing/restapi/embedded_spec.go new file mode 100644 index 0000000..e3b5361 --- /dev/null +++ b/services/billing/restapi/embedded_spec.go @@ -0,0 +1,2624 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Billing", + "title": "Billing Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/billrun": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Show the status report of the billruns present in the system", + "operationId": "ListBillRuns", + "parameters": [ + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/BillRunList" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Try to re-run the failed invoices in all the billruns.", + "operationId": "ReRunAllBillRuns", + "parameters": [ + { + "type": "integer", + "description": "Amount of months to check for failed invoices.", + "name": "months", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/billrun/organization/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Show the status report of the billruns present in the system", + "operationId": "ListBillRunsByOrganization", + "parameters": [ + { + "type": "string", + "description": "Id of the billrun to be re-run.", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/BillRunList" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/billrun/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Get the status report of the billrun requested", + "operationId": "GetBillRun", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Id of the invoice to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/BillRunReport" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Try to re-run the failed invoices in the billrun.", + "operationId": "ReRunBillRun", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Id of the billrun to be re-run.", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Summary for this endpoint", + "operationId": "ListInvoices", + "parameters": [ + { + "description": "Invoice model partially filled to use for the filtering of the invoices", + "name": "model", + "in": "body", + "schema": { + "$ref": "#/definitions/Invoice" + } + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/customer": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve customers' invoices", + "operationId": "ListCustomerInvoices", + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/customer/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve invoices by customer id", + "operationId": "GetInvoicesByCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Generate invoice for the provided customer for the provided time window or last period", + "operationId": "GenerateInvoiceForCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to generate the invoice", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to generate the invoice", + "name": "to", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/reseller": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve resellers' invoices", + "operationId": "ListResellerInvoices", + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/reseller/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve invoices by reseller id", + "operationId": "GetInvoicesByReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Generate invoice for the provided reseller for the provided time window or last period", + "operationId": "GenerateInvoiceForReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to generate the invoice", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to generate the invoice", + "name": "to", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Summary for this endpoint", + "operationId": "GetInvoice", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Id of the invoice to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/Invoice" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "bulk", + "invoice" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/periodicrun": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Periodic run of the bulk generation of invoices", + "operationId": "periodicRun", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime to override the time.now() to simulate other days", + "name": "today", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing the periodic run had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + } + } + } + } + }, + "definitions": { + "BillRun": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + }, + "CreationTimestamp": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + }, + "ExecutionType": { + "type": "string" + }, + "ID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "InvoicesCount": { + "type": "integer" + }, + "InvoicesErrorCount": { + "type": "integer" + }, + "InvoicesErrorList": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "InvoicesList": { + "type": "array", + "items": { + "$ref": "#/definitions/InvoiceMetadata" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "InvoicesProcessedCount": { + "type": "integer" + }, + "OrganizationsInvolved": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "Status": { + "type": "string", + "default": "QUEUED", + "enum": [ + "ERROR", + "FINISHED", + "PROCESSING", + "QUEUED" + ], + "x-go-custom-tag": "gorm:\"default:QUEUED\"" + } + } + }, + "BillRunList": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0 + }, + "CreationTimestamp": { + "type": "string", + "format": "date-time" + }, + "ID": { + "type": "string", + "format": "uuid" + }, + "InvoicesCount": { + "type": "integer" + }, + "InvoicesErrorCount": { + "type": "integer" + }, + "InvoicesErrorList": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "InvoicesProcessedCount": { + "type": "integer" + }, + "OrganizationsInvolved": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "Status": { + "type": "string", + "default": "QUEUED", + "enum": [ + "ERROR", + "FINISHED", + "PROCESSING", + "QUEUED" + ] + } + } + }, + "BillRunReport": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0 + }, + "CreationTimestamp": { + "type": "string", + "format": "date-time" + }, + "ID": { + "type": "string", + "format": "uuid" + }, + "InvoicesCount": { + "type": "integer" + }, + "InvoicesErrorCount": { + "type": "integer" + }, + "InvoicesErrorList": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "InvoicesList": { + "type": "array", + "items": { + "$ref": "#/definitions/InvoiceMetadata" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "InvoicesProcessedCount": { + "type": "integer" + }, + "Status": { + "type": "string", + "default": "QUEUED", + "enum": [ + "ERROR", + "FINISHED", + "PROCESSING", + "QUEUED" + ] + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Invoice": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + }, + "BillRunID": { + "type": "string", + "format": "uuid" + }, + "BillingContact": { + "type": "string" + }, + "Currency": { + "type": "string", + "default": "CHF", + "enum": [ + "CHF", + "EUR", + "USD" + ] + }, + "GenerationTimestamp": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + }, + "ID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Items": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "OrganizationID": { + "type": "string" + }, + "OrganizationName": { + "type": "string" + }, + "OrganizationType": { + "type": "string" + }, + "PaymentDeadline": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"" + }, + "PaymentStatus": { + "type": "string", + "default": "UNPAID", + "enum": [ + "CANCELLED", + "PAID", + "UNPAID" + ] + }, + "PeriodEndDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"" + }, + "PeriodStartDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"" + }, + "Status": { + "type": "string", + "default": "NOT_PROCESSED", + "enum": [ + "ERROR", + "FINISHED", + "NOT_PROCESSED", + "PROCESSING" + ], + "x-go-custom-tag": "gorm:\"default:NOT_PROCESSED\"" + } + } + }, + "InvoiceMetadata": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0 + }, + "Currency": { + "type": "string", + "default": "CHF", + "enum": [ + "CHF", + "EUR", + "USD" + ] + }, + "ID": { + "type": "string", + "format": "uuid" + }, + "OrganizationID": { + "type": "string" + }, + "OrganizationName": { + "type": "string" + }, + "PaymentDeadline": { + "type": "string", + "format": "date" + }, + "PaymentStatus": { + "type": "string", + "default": "UNPAID", + "enum": [ + "CANCELLED", + "PAID", + "UNPAID" + ] + }, + "PeriodEndDate": { + "type": "string", + "format": "date" + }, + "PeriodStartDate": { + "type": "string", + "format": "date" + }, + "Status": { + "type": "string", + "default": "NOT_PROCESSED", + "enum": [ + "ERROR", + "FINISHED", + "NOT_PROCESSED", + "PROCESSING" + ] + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "StringArray": { + "x-go-type": { + "import": { + "package": "github.com/lib/pq" + }, + "type": "StringArray" + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the bulk generations/retrieval of invoices.", + "name": "bulkManagement" + }, + { + "description": "Actions relating to the generation and retrieval of invoices.", + "name": "invoiceManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Billing", + "title": "Billing Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/billrun": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Show the status report of the billruns present in the system", + "operationId": "ListBillRuns", + "parameters": [ + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/BillRunList" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Try to re-run the failed invoices in all the billruns.", + "operationId": "ReRunAllBillRuns", + "parameters": [ + { + "type": "integer", + "description": "Amount of months to check for failed invoices.", + "name": "months", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/billrun/organization/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Show the status report of the billruns present in the system", + "operationId": "ListBillRunsByOrganization", + "parameters": [ + { + "type": "string", + "description": "Id of the billrun to be re-run.", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/BillRunList" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/billrun/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Get the status report of the billrun requested", + "operationId": "GetBillRun", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Id of the invoice to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/BillRunReport" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bulkManagement" + ], + "summary": "Try to re-run the failed invoices in the billrun.", + "operationId": "ReRunBillRun", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Id of the billrun to be re-run.", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Summary for this endpoint", + "operationId": "ListInvoices", + "parameters": [ + { + "description": "Invoice model partially filled to use for the filtering of the invoices", + "name": "model", + "in": "body", + "schema": { + "$ref": "#/definitions/Invoice" + } + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/customer": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve customers' invoices", + "operationId": "ListCustomerInvoices", + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/customer/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve invoices by customer id", + "operationId": "GetInvoicesByCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Generate invoice for the provided customer for the provided time window or last period", + "operationId": "GenerateInvoiceForCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to generate the invoice", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to generate the invoice", + "name": "to", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/reseller": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve resellers' invoices", + "operationId": "ListResellerInvoices", + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/reseller/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Retrieve invoices by reseller id", + "operationId": "GetInvoicesByReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Amount of months to have in the report", + "name": "months", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Invoice" + } + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Generate invoice for the provided reseller for the provided time window or last period", + "operationId": "GenerateInvoiceForReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to generate the invoice", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to generate the invoice", + "name": "to", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/invoice/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "invoiceManagement" + ], + "summary": "Summary for this endpoint", + "operationId": "GetInvoice", + "parameters": [ + { + "type": "string", + "format": "uuid", + "description": "Id of the invoice to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/Invoice" + } + }, + "404": { + "description": "The invoice id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "bulk", + "invoice" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/periodicrun": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Periodic run of the bulk generation of invoices", + "operationId": "periodicRun", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime to override the time.now() to simulate other days", + "name": "today", + "in": "query" + } + ], + "responses": { + "202": { + "description": "The request for processing the periodic run had been added to the queue", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + } + } + } + } + }, + "definitions": { + "BillRun": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + }, + "CreationTimestamp": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + }, + "ExecutionType": { + "type": "string" + }, + "ID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "InvoicesCount": { + "type": "integer" + }, + "InvoicesErrorCount": { + "type": "integer" + }, + "InvoicesErrorList": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "InvoicesList": { + "type": "array", + "items": { + "$ref": "#/definitions/InvoiceMetadata" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "InvoicesProcessedCount": { + "type": "integer" + }, + "OrganizationsInvolved": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "Status": { + "type": "string", + "default": "QUEUED", + "enum": [ + "ERROR", + "FINISHED", + "PROCESSING", + "QUEUED" + ], + "x-go-custom-tag": "gorm:\"default:QUEUED\"" + } + } + }, + "BillRunList": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0 + }, + "CreationTimestamp": { + "type": "string", + "format": "date-time" + }, + "ID": { + "type": "string", + "format": "uuid" + }, + "InvoicesCount": { + "type": "integer" + }, + "InvoicesErrorCount": { + "type": "integer" + }, + "InvoicesErrorList": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "InvoicesProcessedCount": { + "type": "integer" + }, + "OrganizationsInvolved": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "Status": { + "type": "string", + "default": "QUEUED", + "enum": [ + "ERROR", + "FINISHED", + "PROCESSING", + "QUEUED" + ] + } + } + }, + "BillRunReport": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0 + }, + "CreationTimestamp": { + "type": "string", + "format": "date-time" + }, + "ID": { + "type": "string", + "format": "uuid" + }, + "InvoicesCount": { + "type": "integer" + }, + "InvoicesErrorCount": { + "type": "integer" + }, + "InvoicesErrorList": { + "x-go-custom-tag": "gorm:\"type:text[]\"", + "$ref": "#/definitions/StringArray" + }, + "InvoicesList": { + "type": "array", + "items": { + "$ref": "#/definitions/InvoiceMetadata" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "InvoicesProcessedCount": { + "type": "integer" + }, + "Status": { + "type": "string", + "default": "QUEUED", + "enum": [ + "ERROR", + "FINISHED", + "PROCESSING", + "QUEUED" + ] + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Invoice": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + }, + "BillRunID": { + "type": "string", + "format": "uuid" + }, + "BillingContact": { + "type": "string" + }, + "Currency": { + "type": "string", + "default": "CHF", + "enum": [ + "CHF", + "EUR", + "USD" + ] + }, + "GenerationTimestamp": { + "type": "string", + "format": "date-time", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + }, + "ID": { + "type": "string", + "format": "uuid", + "x-go-custom-tag": "gorm:\"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Items": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "OrganizationID": { + "type": "string" + }, + "OrganizationName": { + "type": "string" + }, + "OrganizationType": { + "type": "string" + }, + "PaymentDeadline": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"" + }, + "PaymentStatus": { + "type": "string", + "default": "UNPAID", + "enum": [ + "CANCELLED", + "PAID", + "UNPAID" + ] + }, + "PeriodEndDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"" + }, + "PeriodStartDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"" + }, + "Status": { + "type": "string", + "default": "NOT_PROCESSED", + "enum": [ + "ERROR", + "FINISHED", + "NOT_PROCESSED", + "PROCESSING" + ], + "x-go-custom-tag": "gorm:\"default:NOT_PROCESSED\"" + } + } + }, + "InvoiceMetadata": { + "type": "object", + "properties": { + "AmountInvoiced": { + "type": "number", + "format": "double", + "default": 0 + }, + "Currency": { + "type": "string", + "default": "CHF", + "enum": [ + "CHF", + "EUR", + "USD" + ] + }, + "ID": { + "type": "string", + "format": "uuid" + }, + "OrganizationID": { + "type": "string" + }, + "OrganizationName": { + "type": "string" + }, + "PaymentDeadline": { + "type": "string", + "format": "date" + }, + "PaymentStatus": { + "type": "string", + "default": "UNPAID", + "enum": [ + "CANCELLED", + "PAID", + "UNPAID" + ] + }, + "PeriodEndDate": { + "type": "string", + "format": "date" + }, + "PeriodStartDate": { + "type": "string", + "format": "date" + }, + "Status": { + "type": "string", + "default": "NOT_PROCESSED", + "enum": [ + "ERROR", + "FINISHED", + "NOT_PROCESSED", + "PROCESSING" + ] + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "StringArray": { + "x-go-type": { + "import": { + "package": "github.com/lib/pq" + }, + "type": "StringArray" + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the bulk generations/retrieval of invoices.", + "name": "bulkManagement" + }, + { + "description": "Actions relating to the generation and retrieval of invoices.", + "name": "invoiceManagement" + } + ] +}`)) +} diff --git a/services/billing/restapi/operations/billing_management_api_api.go b/services/billing/restapi/operations/billing_management_api_api.go new file mode 100644 index 0000000..52149fc --- /dev/null +++ b/services/billing/restapi/operations/billing_management_api_api.go @@ -0,0 +1,538 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/bulk_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/invoice_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/trigger_management" +) + +// NewBillingManagementAPIAPI creates a new BillingManagementAPI instance +func NewBillingManagementAPIAPI(spec *loads.Document) *BillingManagementAPIAPI { + return &BillingManagementAPIAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + useSwaggerUI: false, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + InvoiceManagementGenerateInvoiceForCustomerHandler: invoice_management.GenerateInvoiceForCustomerHandlerFunc(func(params invoice_management.GenerateInvoiceForCustomerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.GenerateInvoiceForCustomer has not yet been implemented") + }), + InvoiceManagementGenerateInvoiceForResellerHandler: invoice_management.GenerateInvoiceForResellerHandlerFunc(func(params invoice_management.GenerateInvoiceForResellerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.GenerateInvoiceForReseller has not yet been implemented") + }), + BulkManagementGetBillRunHandler: bulk_management.GetBillRunHandlerFunc(func(params bulk_management.GetBillRunParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bulk_management.GetBillRun has not yet been implemented") + }), + InvoiceManagementGetInvoiceHandler: invoice_management.GetInvoiceHandlerFunc(func(params invoice_management.GetInvoiceParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.GetInvoice has not yet been implemented") + }), + InvoiceManagementGetInvoicesByCustomerHandler: invoice_management.GetInvoicesByCustomerHandlerFunc(func(params invoice_management.GetInvoicesByCustomerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.GetInvoicesByCustomer has not yet been implemented") + }), + InvoiceManagementGetInvoicesByResellerHandler: invoice_management.GetInvoicesByResellerHandlerFunc(func(params invoice_management.GetInvoicesByResellerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.GetInvoicesByReseller has not yet been implemented") + }), + BulkManagementListBillRunsHandler: bulk_management.ListBillRunsHandlerFunc(func(params bulk_management.ListBillRunsParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bulk_management.ListBillRuns has not yet been implemented") + }), + BulkManagementListBillRunsByOrganizationHandler: bulk_management.ListBillRunsByOrganizationHandlerFunc(func(params bulk_management.ListBillRunsByOrganizationParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bulk_management.ListBillRunsByOrganization has not yet been implemented") + }), + InvoiceManagementListCustomerInvoicesHandler: invoice_management.ListCustomerInvoicesHandlerFunc(func(params invoice_management.ListCustomerInvoicesParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.ListCustomerInvoices has not yet been implemented") + }), + InvoiceManagementListInvoicesHandler: invoice_management.ListInvoicesHandlerFunc(func(params invoice_management.ListInvoicesParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.ListInvoices has not yet been implemented") + }), + InvoiceManagementListResellerInvoicesHandler: invoice_management.ListResellerInvoicesHandlerFunc(func(params invoice_management.ListResellerInvoicesParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation invoice_management.ListResellerInvoices has not yet been implemented") + }), + BulkManagementReRunAllBillRunsHandler: bulk_management.ReRunAllBillRunsHandlerFunc(func(params bulk_management.ReRunAllBillRunsParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bulk_management.ReRunAllBillRuns has not yet been implemented") + }), + BulkManagementReRunBillRunHandler: bulk_management.ReRunBillRunHandlerFunc(func(params bulk_management.ReRunBillRunParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bulk_management.ReRunBillRun has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + TriggerManagementPeriodicRunHandler: trigger_management.PeriodicRunHandlerFunc(func(params trigger_management.PeriodicRunParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.PeriodicRun has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*BillingManagementAPIAPI An API which supports creation, deletion, listing etc of Billing */ +type BillingManagementAPIAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + useSwaggerUI bool + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // InvoiceManagementGenerateInvoiceForCustomerHandler sets the operation handler for the generate invoice for customer operation + InvoiceManagementGenerateInvoiceForCustomerHandler invoice_management.GenerateInvoiceForCustomerHandler + // InvoiceManagementGenerateInvoiceForResellerHandler sets the operation handler for the generate invoice for reseller operation + InvoiceManagementGenerateInvoiceForResellerHandler invoice_management.GenerateInvoiceForResellerHandler + // BulkManagementGetBillRunHandler sets the operation handler for the get bill run operation + BulkManagementGetBillRunHandler bulk_management.GetBillRunHandler + // InvoiceManagementGetInvoiceHandler sets the operation handler for the get invoice operation + InvoiceManagementGetInvoiceHandler invoice_management.GetInvoiceHandler + // InvoiceManagementGetInvoicesByCustomerHandler sets the operation handler for the get invoices by customer operation + InvoiceManagementGetInvoicesByCustomerHandler invoice_management.GetInvoicesByCustomerHandler + // InvoiceManagementGetInvoicesByResellerHandler sets the operation handler for the get invoices by reseller operation + InvoiceManagementGetInvoicesByResellerHandler invoice_management.GetInvoicesByResellerHandler + // BulkManagementListBillRunsHandler sets the operation handler for the list bill runs operation + BulkManagementListBillRunsHandler bulk_management.ListBillRunsHandler + // BulkManagementListBillRunsByOrganizationHandler sets the operation handler for the list bill runs by organization operation + BulkManagementListBillRunsByOrganizationHandler bulk_management.ListBillRunsByOrganizationHandler + // InvoiceManagementListCustomerInvoicesHandler sets the operation handler for the list customer invoices operation + InvoiceManagementListCustomerInvoicesHandler invoice_management.ListCustomerInvoicesHandler + // InvoiceManagementListInvoicesHandler sets the operation handler for the list invoices operation + InvoiceManagementListInvoicesHandler invoice_management.ListInvoicesHandler + // InvoiceManagementListResellerInvoicesHandler sets the operation handler for the list reseller invoices operation + InvoiceManagementListResellerInvoicesHandler invoice_management.ListResellerInvoicesHandler + // BulkManagementReRunAllBillRunsHandler sets the operation handler for the re run all bill runs operation + BulkManagementReRunAllBillRunsHandler bulk_management.ReRunAllBillRunsHandler + // BulkManagementReRunBillRunHandler sets the operation handler for the re run bill run operation + BulkManagementReRunBillRunHandler bulk_management.ReRunBillRunHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // TriggerManagementPeriodicRunHandler sets the operation handler for the periodic run operation + TriggerManagementPeriodicRunHandler trigger_management.PeriodicRunHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// UseRedoc for documentation at /docs +func (o *BillingManagementAPIAPI) UseRedoc() { + o.useSwaggerUI = false +} + +// UseSwaggerUI for documentation at /docs +func (o *BillingManagementAPIAPI) UseSwaggerUI() { + o.useSwaggerUI = true +} + +// SetDefaultProduces sets the default produces media type +func (o *BillingManagementAPIAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *BillingManagementAPIAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *BillingManagementAPIAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *BillingManagementAPIAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *BillingManagementAPIAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *BillingManagementAPIAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *BillingManagementAPIAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the BillingManagementAPIAPI +func (o *BillingManagementAPIAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.InvoiceManagementGenerateInvoiceForCustomerHandler == nil { + unregistered = append(unregistered, "invoice_management.GenerateInvoiceForCustomerHandler") + } + if o.InvoiceManagementGenerateInvoiceForResellerHandler == nil { + unregistered = append(unregistered, "invoice_management.GenerateInvoiceForResellerHandler") + } + if o.BulkManagementGetBillRunHandler == nil { + unregistered = append(unregistered, "bulk_management.GetBillRunHandler") + } + if o.InvoiceManagementGetInvoiceHandler == nil { + unregistered = append(unregistered, "invoice_management.GetInvoiceHandler") + } + if o.InvoiceManagementGetInvoicesByCustomerHandler == nil { + unregistered = append(unregistered, "invoice_management.GetInvoicesByCustomerHandler") + } + if o.InvoiceManagementGetInvoicesByResellerHandler == nil { + unregistered = append(unregistered, "invoice_management.GetInvoicesByResellerHandler") + } + if o.BulkManagementListBillRunsHandler == nil { + unregistered = append(unregistered, "bulk_management.ListBillRunsHandler") + } + if o.BulkManagementListBillRunsByOrganizationHandler == nil { + unregistered = append(unregistered, "bulk_management.ListBillRunsByOrganizationHandler") + } + if o.InvoiceManagementListCustomerInvoicesHandler == nil { + unregistered = append(unregistered, "invoice_management.ListCustomerInvoicesHandler") + } + if o.InvoiceManagementListInvoicesHandler == nil { + unregistered = append(unregistered, "invoice_management.ListInvoicesHandler") + } + if o.InvoiceManagementListResellerInvoicesHandler == nil { + unregistered = append(unregistered, "invoice_management.ListResellerInvoicesHandler") + } + if o.BulkManagementReRunAllBillRunsHandler == nil { + unregistered = append(unregistered, "bulk_management.ReRunAllBillRunsHandler") + } + if o.BulkManagementReRunBillRunHandler == nil { + unregistered = append(unregistered, "bulk_management.ReRunBillRunHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.TriggerManagementPeriodicRunHandler == nil { + unregistered = append(unregistered, "trigger_management.PeriodicRunHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *BillingManagementAPIAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *BillingManagementAPIAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *BillingManagementAPIAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *BillingManagementAPIAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *BillingManagementAPIAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *BillingManagementAPIAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the billing management API API +func (o *BillingManagementAPIAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *BillingManagementAPIAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/invoice/customer/{id}"] = invoice_management.NewGenerateInvoiceForCustomer(o.context, o.InvoiceManagementGenerateInvoiceForCustomerHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/invoice/reseller/{id}"] = invoice_management.NewGenerateInvoiceForReseller(o.context, o.InvoiceManagementGenerateInvoiceForResellerHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/billrun/{id}"] = bulk_management.NewGetBillRun(o.context, o.BulkManagementGetBillRunHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/invoice/{id}"] = invoice_management.NewGetInvoice(o.context, o.InvoiceManagementGetInvoiceHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/invoice/customer/{id}"] = invoice_management.NewGetInvoicesByCustomer(o.context, o.InvoiceManagementGetInvoicesByCustomerHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/invoice/reseller/{id}"] = invoice_management.NewGetInvoicesByReseller(o.context, o.InvoiceManagementGetInvoicesByResellerHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/billrun"] = bulk_management.NewListBillRuns(o.context, o.BulkManagementListBillRunsHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/billrun/organization/{id}"] = bulk_management.NewListBillRunsByOrganization(o.context, o.BulkManagementListBillRunsByOrganizationHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/invoice/customer"] = invoice_management.NewListCustomerInvoices(o.context, o.InvoiceManagementListCustomerInvoicesHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/invoice"] = invoice_management.NewListInvoices(o.context, o.InvoiceManagementListInvoicesHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/invoice/reseller"] = invoice_management.NewListResellerInvoices(o.context, o.InvoiceManagementListResellerInvoicesHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/billrun"] = bulk_management.NewReRunAllBillRuns(o.context, o.BulkManagementReRunAllBillRunsHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/billrun/{id}"] = bulk_management.NewReRunBillRun(o.context, o.BulkManagementReRunBillRunHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/periodicrun"] = trigger_management.NewPeriodicRun(o.context, o.TriggerManagementPeriodicRunHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *BillingManagementAPIAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + if o.useSwaggerUI { + return o.context.APIHandlerSwaggerUI(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *BillingManagementAPIAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *BillingManagementAPIAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *BillingManagementAPIAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *BillingManagementAPIAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/services/billing/restapi/operations/bulk_management/get_bill_run.go b/services/billing/restapi/operations/bulk_management/get_bill_run.go new file mode 100644 index 0000000..2a7fe8f --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/get_bill_run.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetBillRunHandlerFunc turns a function with the right signature into a get bill run handler +type GetBillRunHandlerFunc func(GetBillRunParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetBillRunHandlerFunc) Handle(params GetBillRunParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetBillRunHandler interface for that can handle valid get bill run params +type GetBillRunHandler interface { + Handle(GetBillRunParams, interface{}) middleware.Responder +} + +// NewGetBillRun creates a new http.Handler for the get bill run operation +func NewGetBillRun(ctx *middleware.Context, handler GetBillRunHandler) *GetBillRun { + return &GetBillRun{Context: ctx, Handler: handler} +} + +/*GetBillRun swagger:route GET /billrun/{id} bulkManagement getBillRun + +Get the status report of the billrun requested + +*/ +type GetBillRun struct { + Context *middleware.Context + Handler GetBillRunHandler +} + +func (o *GetBillRun) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetBillRunParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/bulk_management/get_bill_run_parameters.go b/services/billing/restapi/operations/bulk_management/get_bill_run_parameters.go new file mode 100644 index 0000000..35bf8df --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/get_bill_run_parameters.go @@ -0,0 +1,91 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetBillRunParams creates a new GetBillRunParams object +// no default values defined in spec. +func NewGetBillRunParams() GetBillRunParams { + + return GetBillRunParams{} +} + +// GetBillRunParams contains all the bound params for the get bill run operation +// typically these are obtained from a http.Request +// +// swagger:parameters GetBillRun +type GetBillRunParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the invoice to be checked + Required: true + In: path + */ + ID strfmt.UUID +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetBillRunParams() beforehand. +func (o *GetBillRunParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetBillRunParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + // Format: uuid + value, err := formats.Parse("uuid", raw) + if err != nil { + return errors.InvalidType("id", "path", "strfmt.UUID", raw) + } + o.ID = *(value.(*strfmt.UUID)) + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetBillRunParams) validateID(formats strfmt.Registry) error { + + if err := validate.FormatOf("id", "path", "uuid", o.ID.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/billing/restapi/operations/bulk_management/get_bill_run_responses.go b/services/billing/restapi/operations/bulk_management/get_bill_run_responses.go new file mode 100644 index 0000000..04f7022 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/get_bill_run_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetBillRunOKCode is the HTTP code returned for type GetBillRunOK +const GetBillRunOKCode int = 200 + +/*GetBillRunOK Description of a successfully operation + +swagger:response getBillRunOK +*/ +type GetBillRunOK struct { + + /* + In: Body + */ + Payload *models.BillRunReport `json:"body,omitempty"` +} + +// NewGetBillRunOK creates GetBillRunOK with default headers values +func NewGetBillRunOK() *GetBillRunOK { + + return &GetBillRunOK{} +} + +// WithPayload adds the payload to the get bill run o k response +func (o *GetBillRunOK) WithPayload(payload *models.BillRunReport) *GetBillRunOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get bill run o k response +func (o *GetBillRunOK) SetPayload(payload *models.BillRunReport) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetBillRunOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetBillRunNotFoundCode is the HTTP code returned for type GetBillRunNotFound +const GetBillRunNotFoundCode int = 404 + +/*GetBillRunNotFound The invoice id provided doesn't exist + +swagger:response getBillRunNotFound +*/ +type GetBillRunNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetBillRunNotFound creates GetBillRunNotFound with default headers values +func NewGetBillRunNotFound() *GetBillRunNotFound { + + return &GetBillRunNotFound{} +} + +// WithPayload adds the payload to the get bill run not found response +func (o *GetBillRunNotFound) WithPayload(payload *models.ErrorResponse) *GetBillRunNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get bill run not found response +func (o *GetBillRunNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetBillRunNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetBillRunInternalServerErrorCode is the HTTP code returned for type GetBillRunInternalServerError +const GetBillRunInternalServerErrorCode int = 500 + +/*GetBillRunInternalServerError Something unexpected happend, error raised + +swagger:response getBillRunInternalServerError +*/ +type GetBillRunInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetBillRunInternalServerError creates GetBillRunInternalServerError with default headers values +func NewGetBillRunInternalServerError() *GetBillRunInternalServerError { + + return &GetBillRunInternalServerError{} +} + +// WithPayload adds the payload to the get bill run internal server error response +func (o *GetBillRunInternalServerError) WithPayload(payload *models.ErrorResponse) *GetBillRunInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get bill run internal server error response +func (o *GetBillRunInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetBillRunInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/bulk_management/get_bill_run_urlbuilder.go b/services/billing/restapi/operations/bulk_management/get_bill_run_urlbuilder.go new file mode 100644 index 0000000..3dbb12e --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/get_bill_run_urlbuilder.go @@ -0,0 +1,101 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// GetBillRunURL generates an URL for the get bill run operation +type GetBillRunURL struct { + ID strfmt.UUID + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetBillRunURL) WithBasePath(bp string) *GetBillRunURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetBillRunURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetBillRunURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/billrun/{id}" + + id := o.ID.String() + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetBillRunURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetBillRunURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetBillRunURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetBillRunURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetBillRunURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetBillRunURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetBillRunURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs.go b/services/billing/restapi/operations/bulk_management/list_bill_runs.go new file mode 100644 index 0000000..21a6e25 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListBillRunsHandlerFunc turns a function with the right signature into a list bill runs handler +type ListBillRunsHandlerFunc func(ListBillRunsParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListBillRunsHandlerFunc) Handle(params ListBillRunsParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListBillRunsHandler interface for that can handle valid list bill runs params +type ListBillRunsHandler interface { + Handle(ListBillRunsParams, interface{}) middleware.Responder +} + +// NewListBillRuns creates a new http.Handler for the list bill runs operation +func NewListBillRuns(ctx *middleware.Context, handler ListBillRunsHandler) *ListBillRuns { + return &ListBillRuns{Context: ctx, Handler: handler} +} + +/*ListBillRuns swagger:route GET /billrun bulkManagement listBillRuns + +Show the status report of the billruns present in the system + +*/ +type ListBillRuns struct { + Context *middleware.Context + Handler ListBillRunsHandler +} + +func (o *ListBillRuns) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListBillRunsParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization.go b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization.go new file mode 100644 index 0000000..ea80b4a --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListBillRunsByOrganizationHandlerFunc turns a function with the right signature into a list bill runs by organization handler +type ListBillRunsByOrganizationHandlerFunc func(ListBillRunsByOrganizationParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListBillRunsByOrganizationHandlerFunc) Handle(params ListBillRunsByOrganizationParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListBillRunsByOrganizationHandler interface for that can handle valid list bill runs by organization params +type ListBillRunsByOrganizationHandler interface { + Handle(ListBillRunsByOrganizationParams, interface{}) middleware.Responder +} + +// NewListBillRunsByOrganization creates a new http.Handler for the list bill runs by organization operation +func NewListBillRunsByOrganization(ctx *middleware.Context, handler ListBillRunsByOrganizationHandler) *ListBillRunsByOrganization { + return &ListBillRunsByOrganization{Context: ctx, Handler: handler} +} + +/*ListBillRunsByOrganization swagger:route GET /billrun/organization/{id} bulkManagement listBillRunsByOrganization + +Show the status report of the billruns present in the system + +*/ +type ListBillRunsByOrganization struct { + Context *middleware.Context + Handler ListBillRunsByOrganizationHandler +} + +func (o *ListBillRunsByOrganization) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListBillRunsByOrganizationParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_parameters.go b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_parameters.go new file mode 100644 index 0000000..f7df35f --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_parameters.go @@ -0,0 +1,107 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewListBillRunsByOrganizationParams creates a new ListBillRunsByOrganizationParams object +// no default values defined in spec. +func NewListBillRunsByOrganizationParams() ListBillRunsByOrganizationParams { + + return ListBillRunsByOrganizationParams{} +} + +// ListBillRunsByOrganizationParams contains all the bound params for the list bill runs by organization operation +// typically these are obtained from a http.Request +// +// swagger:parameters ListBillRunsByOrganization +type ListBillRunsByOrganizationParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the billrun to be re-run. + Required: true + In: path + */ + ID string + /*Amount of months to have in the report + In: query + */ + Months *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListBillRunsByOrganizationParams() beforehand. +func (o *ListBillRunsByOrganizationParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qMonths, qhkMonths, _ := qs.GetOK("months") + if err := o.bindMonths(qMonths, qhkMonths, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *ListBillRunsByOrganizationParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMonths binds and validates parameter Months from query. +func (o *ListBillRunsByOrganizationParams) bindMonths(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("months", "query", "int64", raw) + } + o.Months = &value + + return nil +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_responses.go b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_responses.go new file mode 100644 index 0000000..10d430f --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListBillRunsByOrganizationOKCode is the HTTP code returned for type ListBillRunsByOrganizationOK +const ListBillRunsByOrganizationOKCode int = 200 + +/*ListBillRunsByOrganizationOK Description of a successfully operation + +swagger:response listBillRunsByOrganizationOK +*/ +type ListBillRunsByOrganizationOK struct { + + /* + In: Body + */ + Payload []*models.BillRunList `json:"body,omitempty"` +} + +// NewListBillRunsByOrganizationOK creates ListBillRunsByOrganizationOK with default headers values +func NewListBillRunsByOrganizationOK() *ListBillRunsByOrganizationOK { + + return &ListBillRunsByOrganizationOK{} +} + +// WithPayload adds the payload to the list bill runs by organization o k response +func (o *ListBillRunsByOrganizationOK) WithPayload(payload []*models.BillRunList) *ListBillRunsByOrganizationOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list bill runs by organization o k response +func (o *ListBillRunsByOrganizationOK) SetPayload(payload []*models.BillRunList) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListBillRunsByOrganizationOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.BillRunList, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListBillRunsByOrganizationInternalServerErrorCode is the HTTP code returned for type ListBillRunsByOrganizationInternalServerError +const ListBillRunsByOrganizationInternalServerErrorCode int = 500 + +/*ListBillRunsByOrganizationInternalServerError Something unexpected happend, error raised + +swagger:response listBillRunsByOrganizationInternalServerError +*/ +type ListBillRunsByOrganizationInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListBillRunsByOrganizationInternalServerError creates ListBillRunsByOrganizationInternalServerError with default headers values +func NewListBillRunsByOrganizationInternalServerError() *ListBillRunsByOrganizationInternalServerError { + + return &ListBillRunsByOrganizationInternalServerError{} +} + +// WithPayload adds the payload to the list bill runs by organization internal server error response +func (o *ListBillRunsByOrganizationInternalServerError) WithPayload(payload *models.ErrorResponse) *ListBillRunsByOrganizationInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list bill runs by organization internal server error response +func (o *ListBillRunsByOrganizationInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListBillRunsByOrganizationInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_urlbuilder.go b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_urlbuilder.go new file mode 100644 index 0000000..6649e26 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs_by_organization_urlbuilder.go @@ -0,0 +1,115 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// ListBillRunsByOrganizationURL generates an URL for the list bill runs by organization operation +type ListBillRunsByOrganizationURL struct { + ID string + + Months *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListBillRunsByOrganizationURL) WithBasePath(bp string) *ListBillRunsByOrganizationURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListBillRunsByOrganizationURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListBillRunsByOrganizationURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/billrun/organization/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on ListBillRunsByOrganizationURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var monthsQ string + if o.Months != nil { + monthsQ = swag.FormatInt64(*o.Months) + } + if monthsQ != "" { + qs.Set("months", monthsQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListBillRunsByOrganizationURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListBillRunsByOrganizationURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListBillRunsByOrganizationURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListBillRunsByOrganizationURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListBillRunsByOrganizationURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListBillRunsByOrganizationURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs_parameters.go b/services/billing/restapi/operations/bulk_management/list_bill_runs_parameters.go new file mode 100644 index 0000000..40ec381 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs_parameters.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewListBillRunsParams creates a new ListBillRunsParams object +// no default values defined in spec. +func NewListBillRunsParams() ListBillRunsParams { + + return ListBillRunsParams{} +} + +// ListBillRunsParams contains all the bound params for the list bill runs operation +// typically these are obtained from a http.Request +// +// swagger:parameters ListBillRuns +type ListBillRunsParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Amount of months to have in the report + In: query + */ + Months *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListBillRunsParams() beforehand. +func (o *ListBillRunsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qMonths, qhkMonths, _ := qs.GetOK("months") + if err := o.bindMonths(qMonths, qhkMonths, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindMonths binds and validates parameter Months from query. +func (o *ListBillRunsParams) bindMonths(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("months", "query", "int64", raw) + } + o.Months = &value + + return nil +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs_responses.go b/services/billing/restapi/operations/bulk_management/list_bill_runs_responses.go new file mode 100644 index 0000000..fd05d6f --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListBillRunsOKCode is the HTTP code returned for type ListBillRunsOK +const ListBillRunsOKCode int = 200 + +/*ListBillRunsOK Description of a successfully operation + +swagger:response listBillRunsOK +*/ +type ListBillRunsOK struct { + + /* + In: Body + */ + Payload []*models.BillRunList `json:"body,omitempty"` +} + +// NewListBillRunsOK creates ListBillRunsOK with default headers values +func NewListBillRunsOK() *ListBillRunsOK { + + return &ListBillRunsOK{} +} + +// WithPayload adds the payload to the list bill runs o k response +func (o *ListBillRunsOK) WithPayload(payload []*models.BillRunList) *ListBillRunsOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list bill runs o k response +func (o *ListBillRunsOK) SetPayload(payload []*models.BillRunList) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListBillRunsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.BillRunList, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListBillRunsInternalServerErrorCode is the HTTP code returned for type ListBillRunsInternalServerError +const ListBillRunsInternalServerErrorCode int = 500 + +/*ListBillRunsInternalServerError Something unexpected happend, error raised + +swagger:response listBillRunsInternalServerError +*/ +type ListBillRunsInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListBillRunsInternalServerError creates ListBillRunsInternalServerError with default headers values +func NewListBillRunsInternalServerError() *ListBillRunsInternalServerError { + + return &ListBillRunsInternalServerError{} +} + +// WithPayload adds the payload to the list bill runs internal server error response +func (o *ListBillRunsInternalServerError) WithPayload(payload *models.ErrorResponse) *ListBillRunsInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list bill runs internal server error response +func (o *ListBillRunsInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListBillRunsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/bulk_management/list_bill_runs_urlbuilder.go b/services/billing/restapi/operations/bulk_management/list_bill_runs_urlbuilder.go new file mode 100644 index 0000000..50286e8 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/list_bill_runs_urlbuilder.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/swag" +) + +// ListBillRunsURL generates an URL for the list bill runs operation +type ListBillRunsURL struct { + Months *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListBillRunsURL) WithBasePath(bp string) *ListBillRunsURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListBillRunsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListBillRunsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/billrun" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var monthsQ string + if o.Months != nil { + monthsQ = swag.FormatInt64(*o.Months) + } + if monthsQ != "" { + qs.Set("months", monthsQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListBillRunsURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListBillRunsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListBillRunsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListBillRunsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListBillRunsURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListBillRunsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs.go b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs.go new file mode 100644 index 0000000..8f835ce --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ReRunAllBillRunsHandlerFunc turns a function with the right signature into a re run all bill runs handler +type ReRunAllBillRunsHandlerFunc func(ReRunAllBillRunsParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ReRunAllBillRunsHandlerFunc) Handle(params ReRunAllBillRunsParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ReRunAllBillRunsHandler interface for that can handle valid re run all bill runs params +type ReRunAllBillRunsHandler interface { + Handle(ReRunAllBillRunsParams, interface{}) middleware.Responder +} + +// NewReRunAllBillRuns creates a new http.Handler for the re run all bill runs operation +func NewReRunAllBillRuns(ctx *middleware.Context, handler ReRunAllBillRunsHandler) *ReRunAllBillRuns { + return &ReRunAllBillRuns{Context: ctx, Handler: handler} +} + +/*ReRunAllBillRuns swagger:route PUT /billrun bulkManagement reRunAllBillRuns + +Try to re-run the failed invoices in all the billruns. + +*/ +type ReRunAllBillRuns struct { + Context *middleware.Context + Handler ReRunAllBillRunsHandler +} + +func (o *ReRunAllBillRuns) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewReRunAllBillRunsParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_parameters.go b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_parameters.go new file mode 100644 index 0000000..e777bba --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_parameters.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewReRunAllBillRunsParams creates a new ReRunAllBillRunsParams object +// no default values defined in spec. +func NewReRunAllBillRunsParams() ReRunAllBillRunsParams { + + return ReRunAllBillRunsParams{} +} + +// ReRunAllBillRunsParams contains all the bound params for the re run all bill runs operation +// typically these are obtained from a http.Request +// +// swagger:parameters ReRunAllBillRuns +type ReRunAllBillRunsParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Amount of months to check for failed invoices. + In: query + */ + Months *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewReRunAllBillRunsParams() beforehand. +func (o *ReRunAllBillRunsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qMonths, qhkMonths, _ := qs.GetOK("months") + if err := o.bindMonths(qMonths, qhkMonths, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindMonths binds and validates parameter Months from query. +func (o *ReRunAllBillRunsParams) bindMonths(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("months", "query", "int64", raw) + } + o.Months = &value + + return nil +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_responses.go b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_responses.go new file mode 100644 index 0000000..fa9fbad --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ReRunAllBillRunsAcceptedCode is the HTTP code returned for type ReRunAllBillRunsAccepted +const ReRunAllBillRunsAcceptedCode int = 202 + +/*ReRunAllBillRunsAccepted The request for processing had been added to the queue + +swagger:response reRunAllBillRunsAccepted +*/ +type ReRunAllBillRunsAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewReRunAllBillRunsAccepted creates ReRunAllBillRunsAccepted with default headers values +func NewReRunAllBillRunsAccepted() *ReRunAllBillRunsAccepted { + + return &ReRunAllBillRunsAccepted{} +} + +// WithPayload adds the payload to the re run all bill runs accepted response +func (o *ReRunAllBillRunsAccepted) WithPayload(payload *models.ItemCreatedResponse) *ReRunAllBillRunsAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the re run all bill runs accepted response +func (o *ReRunAllBillRunsAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReRunAllBillRunsAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// ReRunAllBillRunsNotFoundCode is the HTTP code returned for type ReRunAllBillRunsNotFound +const ReRunAllBillRunsNotFoundCode int = 404 + +/*ReRunAllBillRunsNotFound The invoice id provided doesn't exist + +swagger:response reRunAllBillRunsNotFound +*/ +type ReRunAllBillRunsNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewReRunAllBillRunsNotFound creates ReRunAllBillRunsNotFound with default headers values +func NewReRunAllBillRunsNotFound() *ReRunAllBillRunsNotFound { + + return &ReRunAllBillRunsNotFound{} +} + +// WithPayload adds the payload to the re run all bill runs not found response +func (o *ReRunAllBillRunsNotFound) WithPayload(payload *models.ErrorResponse) *ReRunAllBillRunsNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the re run all bill runs not found response +func (o *ReRunAllBillRunsNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReRunAllBillRunsNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// ReRunAllBillRunsInternalServerErrorCode is the HTTP code returned for type ReRunAllBillRunsInternalServerError +const ReRunAllBillRunsInternalServerErrorCode int = 500 + +/*ReRunAllBillRunsInternalServerError Something unexpected happend, error raised + +swagger:response reRunAllBillRunsInternalServerError +*/ +type ReRunAllBillRunsInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewReRunAllBillRunsInternalServerError creates ReRunAllBillRunsInternalServerError with default headers values +func NewReRunAllBillRunsInternalServerError() *ReRunAllBillRunsInternalServerError { + + return &ReRunAllBillRunsInternalServerError{} +} + +// WithPayload adds the payload to the re run all bill runs internal server error response +func (o *ReRunAllBillRunsInternalServerError) WithPayload(payload *models.ErrorResponse) *ReRunAllBillRunsInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the re run all bill runs internal server error response +func (o *ReRunAllBillRunsInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReRunAllBillRunsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_urlbuilder.go b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_urlbuilder.go new file mode 100644 index 0000000..08600ab --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_all_bill_runs_urlbuilder.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/swag" +) + +// ReRunAllBillRunsURL generates an URL for the re run all bill runs operation +type ReRunAllBillRunsURL struct { + Months *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ReRunAllBillRunsURL) WithBasePath(bp string) *ReRunAllBillRunsURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ReRunAllBillRunsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ReRunAllBillRunsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/billrun" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var monthsQ string + if o.Months != nil { + monthsQ = swag.FormatInt64(*o.Months) + } + if monthsQ != "" { + qs.Set("months", monthsQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ReRunAllBillRunsURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ReRunAllBillRunsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ReRunAllBillRunsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ReRunAllBillRunsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ReRunAllBillRunsURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ReRunAllBillRunsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_bill_run.go b/services/billing/restapi/operations/bulk_management/re_run_bill_run.go new file mode 100644 index 0000000..9444a63 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_bill_run.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ReRunBillRunHandlerFunc turns a function with the right signature into a re run bill run handler +type ReRunBillRunHandlerFunc func(ReRunBillRunParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ReRunBillRunHandlerFunc) Handle(params ReRunBillRunParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ReRunBillRunHandler interface for that can handle valid re run bill run params +type ReRunBillRunHandler interface { + Handle(ReRunBillRunParams, interface{}) middleware.Responder +} + +// NewReRunBillRun creates a new http.Handler for the re run bill run operation +func NewReRunBillRun(ctx *middleware.Context, handler ReRunBillRunHandler) *ReRunBillRun { + return &ReRunBillRun{Context: ctx, Handler: handler} +} + +/*ReRunBillRun swagger:route PUT /billrun/{id} bulkManagement reRunBillRun + +Try to re-run the failed invoices in the billrun. + +*/ +type ReRunBillRun struct { + Context *middleware.Context + Handler ReRunBillRunHandler +} + +func (o *ReRunBillRun) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewReRunBillRunParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_bill_run_parameters.go b/services/billing/restapi/operations/bulk_management/re_run_bill_run_parameters.go new file mode 100644 index 0000000..b8e11db --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_bill_run_parameters.go @@ -0,0 +1,91 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewReRunBillRunParams creates a new ReRunBillRunParams object +// no default values defined in spec. +func NewReRunBillRunParams() ReRunBillRunParams { + + return ReRunBillRunParams{} +} + +// ReRunBillRunParams contains all the bound params for the re run bill run operation +// typically these are obtained from a http.Request +// +// swagger:parameters ReRunBillRun +type ReRunBillRunParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the billrun to be re-run. + Required: true + In: path + */ + ID strfmt.UUID +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewReRunBillRunParams() beforehand. +func (o *ReRunBillRunParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *ReRunBillRunParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + // Format: uuid + value, err := formats.Parse("uuid", raw) + if err != nil { + return errors.InvalidType("id", "path", "strfmt.UUID", raw) + } + o.ID = *(value.(*strfmt.UUID)) + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *ReRunBillRunParams) validateID(formats strfmt.Registry) error { + + if err := validate.FormatOf("id", "path", "uuid", o.ID.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_bill_run_responses.go b/services/billing/restapi/operations/bulk_management/re_run_bill_run_responses.go new file mode 100644 index 0000000..46f2548 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_bill_run_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ReRunBillRunAcceptedCode is the HTTP code returned for type ReRunBillRunAccepted +const ReRunBillRunAcceptedCode int = 202 + +/*ReRunBillRunAccepted The request for processing had been added to the queue + +swagger:response reRunBillRunAccepted +*/ +type ReRunBillRunAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewReRunBillRunAccepted creates ReRunBillRunAccepted with default headers values +func NewReRunBillRunAccepted() *ReRunBillRunAccepted { + + return &ReRunBillRunAccepted{} +} + +// WithPayload adds the payload to the re run bill run accepted response +func (o *ReRunBillRunAccepted) WithPayload(payload *models.ItemCreatedResponse) *ReRunBillRunAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the re run bill run accepted response +func (o *ReRunBillRunAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReRunBillRunAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// ReRunBillRunNotFoundCode is the HTTP code returned for type ReRunBillRunNotFound +const ReRunBillRunNotFoundCode int = 404 + +/*ReRunBillRunNotFound The invoice id provided doesn't exist + +swagger:response reRunBillRunNotFound +*/ +type ReRunBillRunNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewReRunBillRunNotFound creates ReRunBillRunNotFound with default headers values +func NewReRunBillRunNotFound() *ReRunBillRunNotFound { + + return &ReRunBillRunNotFound{} +} + +// WithPayload adds the payload to the re run bill run not found response +func (o *ReRunBillRunNotFound) WithPayload(payload *models.ErrorResponse) *ReRunBillRunNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the re run bill run not found response +func (o *ReRunBillRunNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReRunBillRunNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// ReRunBillRunInternalServerErrorCode is the HTTP code returned for type ReRunBillRunInternalServerError +const ReRunBillRunInternalServerErrorCode int = 500 + +/*ReRunBillRunInternalServerError Something unexpected happend, error raised + +swagger:response reRunBillRunInternalServerError +*/ +type ReRunBillRunInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewReRunBillRunInternalServerError creates ReRunBillRunInternalServerError with default headers values +func NewReRunBillRunInternalServerError() *ReRunBillRunInternalServerError { + + return &ReRunBillRunInternalServerError{} +} + +// WithPayload adds the payload to the re run bill run internal server error response +func (o *ReRunBillRunInternalServerError) WithPayload(payload *models.ErrorResponse) *ReRunBillRunInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the re run bill run internal server error response +func (o *ReRunBillRunInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReRunBillRunInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/bulk_management/re_run_bill_run_urlbuilder.go b/services/billing/restapi/operations/bulk_management/re_run_bill_run_urlbuilder.go new file mode 100644 index 0000000..f8b0624 --- /dev/null +++ b/services/billing/restapi/operations/bulk_management/re_run_bill_run_urlbuilder.go @@ -0,0 +1,101 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bulk_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// ReRunBillRunURL generates an URL for the re run bill run operation +type ReRunBillRunURL struct { + ID strfmt.UUID + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ReRunBillRunURL) WithBasePath(bp string) *ReRunBillRunURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ReRunBillRunURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ReRunBillRunURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/billrun/{id}" + + id := o.ID.String() + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on ReRunBillRunURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ReRunBillRunURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ReRunBillRunURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ReRunBillRunURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ReRunBillRunURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ReRunBillRunURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ReRunBillRunURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer.go new file mode 100644 index 0000000..30e3759 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GenerateInvoiceForCustomerHandlerFunc turns a function with the right signature into a generate invoice for customer handler +type GenerateInvoiceForCustomerHandlerFunc func(GenerateInvoiceForCustomerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GenerateInvoiceForCustomerHandlerFunc) Handle(params GenerateInvoiceForCustomerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GenerateInvoiceForCustomerHandler interface for that can handle valid generate invoice for customer params +type GenerateInvoiceForCustomerHandler interface { + Handle(GenerateInvoiceForCustomerParams, interface{}) middleware.Responder +} + +// NewGenerateInvoiceForCustomer creates a new http.Handler for the generate invoice for customer operation +func NewGenerateInvoiceForCustomer(ctx *middleware.Context, handler GenerateInvoiceForCustomerHandler) *GenerateInvoiceForCustomer { + return &GenerateInvoiceForCustomer{Context: ctx, Handler: handler} +} + +/*GenerateInvoiceForCustomer swagger:route POST /invoice/customer/{id} invoiceManagement generateInvoiceForCustomer + +Generate invoice for the provided customer for the provided time window or last period + +*/ +type GenerateInvoiceForCustomer struct { + Context *middleware.Context + Handler GenerateInvoiceForCustomerHandler +} + +func (o *GenerateInvoiceForCustomer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGenerateInvoiceForCustomerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_parameters.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_parameters.go new file mode 100644 index 0000000..9b5ad4f --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_parameters.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGenerateInvoiceForCustomerParams creates a new GenerateInvoiceForCustomerParams object +// no default values defined in spec. +func NewGenerateInvoiceForCustomerParams() GenerateInvoiceForCustomerParams { + + return GenerateInvoiceForCustomerParams{} +} + +// GenerateInvoiceForCustomerParams contains all the bound params for the generate invoice for customer operation +// typically these are obtained from a http.Request +// +// swagger:parameters GenerateInvoiceForCustomer +type GenerateInvoiceForCustomerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to generate the invoice + In: query + */ + From *strfmt.DateTime + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Datetime until which to generate the invoice + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGenerateInvoiceForCustomerParams() beforehand. +func (o *GenerateInvoiceForCustomerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GenerateInvoiceForCustomerParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *GenerateInvoiceForCustomerParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GenerateInvoiceForCustomerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GenerateInvoiceForCustomerParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *GenerateInvoiceForCustomerParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_responses.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_responses.go new file mode 100644 index 0000000..a10bfb9 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GenerateInvoiceForCustomerAcceptedCode is the HTTP code returned for type GenerateInvoiceForCustomerAccepted +const GenerateInvoiceForCustomerAcceptedCode int = 202 + +/*GenerateInvoiceForCustomerAccepted The request for processing had been added to the queue + +swagger:response generateInvoiceForCustomerAccepted +*/ +type GenerateInvoiceForCustomerAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewGenerateInvoiceForCustomerAccepted creates GenerateInvoiceForCustomerAccepted with default headers values +func NewGenerateInvoiceForCustomerAccepted() *GenerateInvoiceForCustomerAccepted { + + return &GenerateInvoiceForCustomerAccepted{} +} + +// WithPayload adds the payload to the generate invoice for customer accepted response +func (o *GenerateInvoiceForCustomerAccepted) WithPayload(payload *models.ItemCreatedResponse) *GenerateInvoiceForCustomerAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the generate invoice for customer accepted response +func (o *GenerateInvoiceForCustomerAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GenerateInvoiceForCustomerAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GenerateInvoiceForCustomerBadRequestCode is the HTTP code returned for type GenerateInvoiceForCustomerBadRequest +const GenerateInvoiceForCustomerBadRequestCode int = 400 + +/*GenerateInvoiceForCustomerBadRequest Invalid input, object invalid + +swagger:response generateInvoiceForCustomerBadRequest +*/ +type GenerateInvoiceForCustomerBadRequest struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGenerateInvoiceForCustomerBadRequest creates GenerateInvoiceForCustomerBadRequest with default headers values +func NewGenerateInvoiceForCustomerBadRequest() *GenerateInvoiceForCustomerBadRequest { + + return &GenerateInvoiceForCustomerBadRequest{} +} + +// WithPayload adds the payload to the generate invoice for customer bad request response +func (o *GenerateInvoiceForCustomerBadRequest) WithPayload(payload *models.ErrorResponse) *GenerateInvoiceForCustomerBadRequest { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the generate invoice for customer bad request response +func (o *GenerateInvoiceForCustomerBadRequest) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GenerateInvoiceForCustomerBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(400) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GenerateInvoiceForCustomerInternalServerErrorCode is the HTTP code returned for type GenerateInvoiceForCustomerInternalServerError +const GenerateInvoiceForCustomerInternalServerErrorCode int = 500 + +/*GenerateInvoiceForCustomerInternalServerError Something unexpected happend, error raised + +swagger:response generateInvoiceForCustomerInternalServerError +*/ +type GenerateInvoiceForCustomerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGenerateInvoiceForCustomerInternalServerError creates GenerateInvoiceForCustomerInternalServerError with default headers values +func NewGenerateInvoiceForCustomerInternalServerError() *GenerateInvoiceForCustomerInternalServerError { + + return &GenerateInvoiceForCustomerInternalServerError{} +} + +// WithPayload adds the payload to the generate invoice for customer internal server error response +func (o *GenerateInvoiceForCustomerInternalServerError) WithPayload(payload *models.ErrorResponse) *GenerateInvoiceForCustomerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the generate invoice for customer internal server error response +func (o *GenerateInvoiceForCustomerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GenerateInvoiceForCustomerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_urlbuilder.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_urlbuilder.go new file mode 100644 index 0000000..7b069ee --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_customer_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// GenerateInvoiceForCustomerURL generates an URL for the generate invoice for customer operation +type GenerateInvoiceForCustomerURL struct { + ID string + + From *strfmt.DateTime + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GenerateInvoiceForCustomerURL) WithBasePath(bp string) *GenerateInvoiceForCustomerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GenerateInvoiceForCustomerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GenerateInvoiceForCustomerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice/customer/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GenerateInvoiceForCustomerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GenerateInvoiceForCustomerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GenerateInvoiceForCustomerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GenerateInvoiceForCustomerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GenerateInvoiceForCustomerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GenerateInvoiceForCustomerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GenerateInvoiceForCustomerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller.go new file mode 100644 index 0000000..ee3bd8f --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GenerateInvoiceForResellerHandlerFunc turns a function with the right signature into a generate invoice for reseller handler +type GenerateInvoiceForResellerHandlerFunc func(GenerateInvoiceForResellerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GenerateInvoiceForResellerHandlerFunc) Handle(params GenerateInvoiceForResellerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GenerateInvoiceForResellerHandler interface for that can handle valid generate invoice for reseller params +type GenerateInvoiceForResellerHandler interface { + Handle(GenerateInvoiceForResellerParams, interface{}) middleware.Responder +} + +// NewGenerateInvoiceForReseller creates a new http.Handler for the generate invoice for reseller operation +func NewGenerateInvoiceForReseller(ctx *middleware.Context, handler GenerateInvoiceForResellerHandler) *GenerateInvoiceForReseller { + return &GenerateInvoiceForReseller{Context: ctx, Handler: handler} +} + +/*GenerateInvoiceForReseller swagger:route POST /invoice/reseller/{id} invoiceManagement generateInvoiceForReseller + +Generate invoice for the provided reseller for the provided time window or last period + +*/ +type GenerateInvoiceForReseller struct { + Context *middleware.Context + Handler GenerateInvoiceForResellerHandler +} + +func (o *GenerateInvoiceForReseller) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGenerateInvoiceForResellerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_parameters.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_parameters.go new file mode 100644 index 0000000..585737d --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_parameters.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGenerateInvoiceForResellerParams creates a new GenerateInvoiceForResellerParams object +// no default values defined in spec. +func NewGenerateInvoiceForResellerParams() GenerateInvoiceForResellerParams { + + return GenerateInvoiceForResellerParams{} +} + +// GenerateInvoiceForResellerParams contains all the bound params for the generate invoice for reseller operation +// typically these are obtained from a http.Request +// +// swagger:parameters GenerateInvoiceForReseller +type GenerateInvoiceForResellerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to generate the invoice + In: query + */ + From *strfmt.DateTime + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Datetime until which to generate the invoice + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGenerateInvoiceForResellerParams() beforehand. +func (o *GenerateInvoiceForResellerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GenerateInvoiceForResellerParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *GenerateInvoiceForResellerParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GenerateInvoiceForResellerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GenerateInvoiceForResellerParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *GenerateInvoiceForResellerParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_responses.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_responses.go new file mode 100644 index 0000000..4df9c5d --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GenerateInvoiceForResellerAcceptedCode is the HTTP code returned for type GenerateInvoiceForResellerAccepted +const GenerateInvoiceForResellerAcceptedCode int = 202 + +/*GenerateInvoiceForResellerAccepted The request for processing had been added to the queue + +swagger:response generateInvoiceForResellerAccepted +*/ +type GenerateInvoiceForResellerAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewGenerateInvoiceForResellerAccepted creates GenerateInvoiceForResellerAccepted with default headers values +func NewGenerateInvoiceForResellerAccepted() *GenerateInvoiceForResellerAccepted { + + return &GenerateInvoiceForResellerAccepted{} +} + +// WithPayload adds the payload to the generate invoice for reseller accepted response +func (o *GenerateInvoiceForResellerAccepted) WithPayload(payload *models.ItemCreatedResponse) *GenerateInvoiceForResellerAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the generate invoice for reseller accepted response +func (o *GenerateInvoiceForResellerAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GenerateInvoiceForResellerAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GenerateInvoiceForResellerBadRequestCode is the HTTP code returned for type GenerateInvoiceForResellerBadRequest +const GenerateInvoiceForResellerBadRequestCode int = 400 + +/*GenerateInvoiceForResellerBadRequest Invalid input, object invalid + +swagger:response generateInvoiceForResellerBadRequest +*/ +type GenerateInvoiceForResellerBadRequest struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGenerateInvoiceForResellerBadRequest creates GenerateInvoiceForResellerBadRequest with default headers values +func NewGenerateInvoiceForResellerBadRequest() *GenerateInvoiceForResellerBadRequest { + + return &GenerateInvoiceForResellerBadRequest{} +} + +// WithPayload adds the payload to the generate invoice for reseller bad request response +func (o *GenerateInvoiceForResellerBadRequest) WithPayload(payload *models.ErrorResponse) *GenerateInvoiceForResellerBadRequest { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the generate invoice for reseller bad request response +func (o *GenerateInvoiceForResellerBadRequest) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GenerateInvoiceForResellerBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(400) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GenerateInvoiceForResellerInternalServerErrorCode is the HTTP code returned for type GenerateInvoiceForResellerInternalServerError +const GenerateInvoiceForResellerInternalServerErrorCode int = 500 + +/*GenerateInvoiceForResellerInternalServerError Something unexpected happend, error raised + +swagger:response generateInvoiceForResellerInternalServerError +*/ +type GenerateInvoiceForResellerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGenerateInvoiceForResellerInternalServerError creates GenerateInvoiceForResellerInternalServerError with default headers values +func NewGenerateInvoiceForResellerInternalServerError() *GenerateInvoiceForResellerInternalServerError { + + return &GenerateInvoiceForResellerInternalServerError{} +} + +// WithPayload adds the payload to the generate invoice for reseller internal server error response +func (o *GenerateInvoiceForResellerInternalServerError) WithPayload(payload *models.ErrorResponse) *GenerateInvoiceForResellerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the generate invoice for reseller internal server error response +func (o *GenerateInvoiceForResellerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GenerateInvoiceForResellerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_urlbuilder.go b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_urlbuilder.go new file mode 100644 index 0000000..721a5b0 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/generate_invoice_for_reseller_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// GenerateInvoiceForResellerURL generates an URL for the generate invoice for reseller operation +type GenerateInvoiceForResellerURL struct { + ID string + + From *strfmt.DateTime + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GenerateInvoiceForResellerURL) WithBasePath(bp string) *GenerateInvoiceForResellerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GenerateInvoiceForResellerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GenerateInvoiceForResellerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice/reseller/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GenerateInvoiceForResellerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GenerateInvoiceForResellerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GenerateInvoiceForResellerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GenerateInvoiceForResellerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GenerateInvoiceForResellerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GenerateInvoiceForResellerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GenerateInvoiceForResellerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoice.go b/services/billing/restapi/operations/invoice_management/get_invoice.go new file mode 100644 index 0000000..6f95702 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoice.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetInvoiceHandlerFunc turns a function with the right signature into a get invoice handler +type GetInvoiceHandlerFunc func(GetInvoiceParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetInvoiceHandlerFunc) Handle(params GetInvoiceParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetInvoiceHandler interface for that can handle valid get invoice params +type GetInvoiceHandler interface { + Handle(GetInvoiceParams, interface{}) middleware.Responder +} + +// NewGetInvoice creates a new http.Handler for the get invoice operation +func NewGetInvoice(ctx *middleware.Context, handler GetInvoiceHandler) *GetInvoice { + return &GetInvoice{Context: ctx, Handler: handler} +} + +/*GetInvoice swagger:route GET /invoice/{id} invoiceManagement getInvoice + +Summary for this endpoint + +*/ +type GetInvoice struct { + Context *middleware.Context + Handler GetInvoiceHandler +} + +func (o *GetInvoice) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetInvoiceParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoice_parameters.go b/services/billing/restapi/operations/invoice_management/get_invoice_parameters.go new file mode 100644 index 0000000..0efdf60 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoice_parameters.go @@ -0,0 +1,91 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetInvoiceParams creates a new GetInvoiceParams object +// no default values defined in spec. +func NewGetInvoiceParams() GetInvoiceParams { + + return GetInvoiceParams{} +} + +// GetInvoiceParams contains all the bound params for the get invoice operation +// typically these are obtained from a http.Request +// +// swagger:parameters GetInvoice +type GetInvoiceParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the invoice to be checked + Required: true + In: path + */ + ID strfmt.UUID +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetInvoiceParams() beforehand. +func (o *GetInvoiceParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetInvoiceParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + // Format: uuid + value, err := formats.Parse("uuid", raw) + if err != nil { + return errors.InvalidType("id", "path", "strfmt.UUID", raw) + } + o.ID = *(value.(*strfmt.UUID)) + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetInvoiceParams) validateID(formats strfmt.Registry) error { + + if err := validate.FormatOf("id", "path", "uuid", o.ID.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoice_responses.go b/services/billing/restapi/operations/invoice_management/get_invoice_responses.go new file mode 100644 index 0000000..30b8458 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoice_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetInvoiceOKCode is the HTTP code returned for type GetInvoiceOK +const GetInvoiceOKCode int = 200 + +/*GetInvoiceOK Description of a successfully operation + +swagger:response getInvoiceOK +*/ +type GetInvoiceOK struct { + + /* + In: Body + */ + Payload *models.Invoice `json:"body,omitempty"` +} + +// NewGetInvoiceOK creates GetInvoiceOK with default headers values +func NewGetInvoiceOK() *GetInvoiceOK { + + return &GetInvoiceOK{} +} + +// WithPayload adds the payload to the get invoice o k response +func (o *GetInvoiceOK) WithPayload(payload *models.Invoice) *GetInvoiceOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoice o k response +func (o *GetInvoiceOK) SetPayload(payload *models.Invoice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoiceOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetInvoiceNotFoundCode is the HTTP code returned for type GetInvoiceNotFound +const GetInvoiceNotFoundCode int = 404 + +/*GetInvoiceNotFound The invoice id provided doesn't exist + +swagger:response getInvoiceNotFound +*/ +type GetInvoiceNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetInvoiceNotFound creates GetInvoiceNotFound with default headers values +func NewGetInvoiceNotFound() *GetInvoiceNotFound { + + return &GetInvoiceNotFound{} +} + +// WithPayload adds the payload to the get invoice not found response +func (o *GetInvoiceNotFound) WithPayload(payload *models.ErrorResponse) *GetInvoiceNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoice not found response +func (o *GetInvoiceNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoiceNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetInvoiceInternalServerErrorCode is the HTTP code returned for type GetInvoiceInternalServerError +const GetInvoiceInternalServerErrorCode int = 500 + +/*GetInvoiceInternalServerError Something unexpected happend, error raised + +swagger:response getInvoiceInternalServerError +*/ +type GetInvoiceInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetInvoiceInternalServerError creates GetInvoiceInternalServerError with default headers values +func NewGetInvoiceInternalServerError() *GetInvoiceInternalServerError { + + return &GetInvoiceInternalServerError{} +} + +// WithPayload adds the payload to the get invoice internal server error response +func (o *GetInvoiceInternalServerError) WithPayload(payload *models.ErrorResponse) *GetInvoiceInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoice internal server error response +func (o *GetInvoiceInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoiceInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoice_urlbuilder.go b/services/billing/restapi/operations/invoice_management/get_invoice_urlbuilder.go new file mode 100644 index 0000000..56f9d51 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoice_urlbuilder.go @@ -0,0 +1,101 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// GetInvoiceURL generates an URL for the get invoice operation +type GetInvoiceURL struct { + ID strfmt.UUID + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetInvoiceURL) WithBasePath(bp string) *GetInvoiceURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetInvoiceURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetInvoiceURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice/{id}" + + id := o.ID.String() + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetInvoiceURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetInvoiceURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetInvoiceURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetInvoiceURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetInvoiceURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetInvoiceURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetInvoiceURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_customer.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer.go new file mode 100644 index 0000000..d3a9bcd --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetInvoicesByCustomerHandlerFunc turns a function with the right signature into a get invoices by customer handler +type GetInvoicesByCustomerHandlerFunc func(GetInvoicesByCustomerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetInvoicesByCustomerHandlerFunc) Handle(params GetInvoicesByCustomerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetInvoicesByCustomerHandler interface for that can handle valid get invoices by customer params +type GetInvoicesByCustomerHandler interface { + Handle(GetInvoicesByCustomerParams, interface{}) middleware.Responder +} + +// NewGetInvoicesByCustomer creates a new http.Handler for the get invoices by customer operation +func NewGetInvoicesByCustomer(ctx *middleware.Context, handler GetInvoicesByCustomerHandler) *GetInvoicesByCustomer { + return &GetInvoicesByCustomer{Context: ctx, Handler: handler} +} + +/*GetInvoicesByCustomer swagger:route GET /invoice/customer/{id} invoiceManagement getInvoicesByCustomer + +Retrieve invoices by customer id + +*/ +type GetInvoicesByCustomer struct { + Context *middleware.Context + Handler GetInvoicesByCustomerHandler +} + +func (o *GetInvoicesByCustomer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetInvoicesByCustomerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_parameters.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_parameters.go new file mode 100644 index 0000000..b260c20 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_parameters.go @@ -0,0 +1,107 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetInvoicesByCustomerParams creates a new GetInvoicesByCustomerParams object +// no default values defined in spec. +func NewGetInvoicesByCustomerParams() GetInvoicesByCustomerParams { + + return GetInvoicesByCustomerParams{} +} + +// GetInvoicesByCustomerParams contains all the bound params for the get invoices by customer operation +// typically these are obtained from a http.Request +// +// swagger:parameters GetInvoicesByCustomer +type GetInvoicesByCustomerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Amount of months to have in the report + In: query + */ + Months *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetInvoicesByCustomerParams() beforehand. +func (o *GetInvoicesByCustomerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qMonths, qhkMonths, _ := qs.GetOK("months") + if err := o.bindMonths(qMonths, qhkMonths, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetInvoicesByCustomerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMonths binds and validates parameter Months from query. +func (o *GetInvoicesByCustomerParams) bindMonths(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("months", "query", "int64", raw) + } + o.Months = &value + + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_responses.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_responses.go new file mode 100644 index 0000000..9eb296d --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_responses.go @@ -0,0 +1,149 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetInvoicesByCustomerOKCode is the HTTP code returned for type GetInvoicesByCustomerOK +const GetInvoicesByCustomerOKCode int = 200 + +/*GetInvoicesByCustomerOK Description of a successfully operation + +swagger:response getInvoicesByCustomerOK +*/ +type GetInvoicesByCustomerOK struct { + + /* + In: Body + */ + Payload []*models.Invoice `json:"body,omitempty"` +} + +// NewGetInvoicesByCustomerOK creates GetInvoicesByCustomerOK with default headers values +func NewGetInvoicesByCustomerOK() *GetInvoicesByCustomerOK { + + return &GetInvoicesByCustomerOK{} +} + +// WithPayload adds the payload to the get invoices by customer o k response +func (o *GetInvoicesByCustomerOK) WithPayload(payload []*models.Invoice) *GetInvoicesByCustomerOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoices by customer o k response +func (o *GetInvoicesByCustomerOK) SetPayload(payload []*models.Invoice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoicesByCustomerOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Invoice, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetInvoicesByCustomerNotFoundCode is the HTTP code returned for type GetInvoicesByCustomerNotFound +const GetInvoicesByCustomerNotFoundCode int = 404 + +/*GetInvoicesByCustomerNotFound The invoice id provided doesn't exist + +swagger:response getInvoicesByCustomerNotFound +*/ +type GetInvoicesByCustomerNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetInvoicesByCustomerNotFound creates GetInvoicesByCustomerNotFound with default headers values +func NewGetInvoicesByCustomerNotFound() *GetInvoicesByCustomerNotFound { + + return &GetInvoicesByCustomerNotFound{} +} + +// WithPayload adds the payload to the get invoices by customer not found response +func (o *GetInvoicesByCustomerNotFound) WithPayload(payload *models.ErrorResponse) *GetInvoicesByCustomerNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoices by customer not found response +func (o *GetInvoicesByCustomerNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoicesByCustomerNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetInvoicesByCustomerInternalServerErrorCode is the HTTP code returned for type GetInvoicesByCustomerInternalServerError +const GetInvoicesByCustomerInternalServerErrorCode int = 500 + +/*GetInvoicesByCustomerInternalServerError Something unexpected happend, error raised + +swagger:response getInvoicesByCustomerInternalServerError +*/ +type GetInvoicesByCustomerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetInvoicesByCustomerInternalServerError creates GetInvoicesByCustomerInternalServerError with default headers values +func NewGetInvoicesByCustomerInternalServerError() *GetInvoicesByCustomerInternalServerError { + + return &GetInvoicesByCustomerInternalServerError{} +} + +// WithPayload adds the payload to the get invoices by customer internal server error response +func (o *GetInvoicesByCustomerInternalServerError) WithPayload(payload *models.ErrorResponse) *GetInvoicesByCustomerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoices by customer internal server error response +func (o *GetInvoicesByCustomerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoicesByCustomerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_urlbuilder.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_urlbuilder.go new file mode 100644 index 0000000..8f114f1 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_customer_urlbuilder.go @@ -0,0 +1,115 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// GetInvoicesByCustomerURL generates an URL for the get invoices by customer operation +type GetInvoicesByCustomerURL struct { + ID string + + Months *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetInvoicesByCustomerURL) WithBasePath(bp string) *GetInvoicesByCustomerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetInvoicesByCustomerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetInvoicesByCustomerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice/customer/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetInvoicesByCustomerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var monthsQ string + if o.Months != nil { + monthsQ = swag.FormatInt64(*o.Months) + } + if monthsQ != "" { + qs.Set("months", monthsQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetInvoicesByCustomerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetInvoicesByCustomerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetInvoicesByCustomerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetInvoicesByCustomerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetInvoicesByCustomerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetInvoicesByCustomerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller.go new file mode 100644 index 0000000..7d506f2 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetInvoicesByResellerHandlerFunc turns a function with the right signature into a get invoices by reseller handler +type GetInvoicesByResellerHandlerFunc func(GetInvoicesByResellerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetInvoicesByResellerHandlerFunc) Handle(params GetInvoicesByResellerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetInvoicesByResellerHandler interface for that can handle valid get invoices by reseller params +type GetInvoicesByResellerHandler interface { + Handle(GetInvoicesByResellerParams, interface{}) middleware.Responder +} + +// NewGetInvoicesByReseller creates a new http.Handler for the get invoices by reseller operation +func NewGetInvoicesByReseller(ctx *middleware.Context, handler GetInvoicesByResellerHandler) *GetInvoicesByReseller { + return &GetInvoicesByReseller{Context: ctx, Handler: handler} +} + +/*GetInvoicesByReseller swagger:route GET /invoice/reseller/{id} invoiceManagement getInvoicesByReseller + +Retrieve invoices by reseller id + +*/ +type GetInvoicesByReseller struct { + Context *middleware.Context + Handler GetInvoicesByResellerHandler +} + +func (o *GetInvoicesByReseller) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetInvoicesByResellerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_parameters.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_parameters.go new file mode 100644 index 0000000..4f1862d --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_parameters.go @@ -0,0 +1,107 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetInvoicesByResellerParams creates a new GetInvoicesByResellerParams object +// no default values defined in spec. +func NewGetInvoicesByResellerParams() GetInvoicesByResellerParams { + + return GetInvoicesByResellerParams{} +} + +// GetInvoicesByResellerParams contains all the bound params for the get invoices by reseller operation +// typically these are obtained from a http.Request +// +// swagger:parameters GetInvoicesByReseller +type GetInvoicesByResellerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Amount of months to have in the report + In: query + */ + Months *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetInvoicesByResellerParams() beforehand. +func (o *GetInvoicesByResellerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qMonths, qhkMonths, _ := qs.GetOK("months") + if err := o.bindMonths(qMonths, qhkMonths, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetInvoicesByResellerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMonths binds and validates parameter Months from query. +func (o *GetInvoicesByResellerParams) bindMonths(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("months", "query", "int64", raw) + } + o.Months = &value + + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_responses.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_responses.go new file mode 100644 index 0000000..a38a52d --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_responses.go @@ -0,0 +1,149 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetInvoicesByResellerOKCode is the HTTP code returned for type GetInvoicesByResellerOK +const GetInvoicesByResellerOKCode int = 200 + +/*GetInvoicesByResellerOK Description of a successfully operation + +swagger:response getInvoicesByResellerOK +*/ +type GetInvoicesByResellerOK struct { + + /* + In: Body + */ + Payload []*models.Invoice `json:"body,omitempty"` +} + +// NewGetInvoicesByResellerOK creates GetInvoicesByResellerOK with default headers values +func NewGetInvoicesByResellerOK() *GetInvoicesByResellerOK { + + return &GetInvoicesByResellerOK{} +} + +// WithPayload adds the payload to the get invoices by reseller o k response +func (o *GetInvoicesByResellerOK) WithPayload(payload []*models.Invoice) *GetInvoicesByResellerOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoices by reseller o k response +func (o *GetInvoicesByResellerOK) SetPayload(payload []*models.Invoice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoicesByResellerOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Invoice, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetInvoicesByResellerNotFoundCode is the HTTP code returned for type GetInvoicesByResellerNotFound +const GetInvoicesByResellerNotFoundCode int = 404 + +/*GetInvoicesByResellerNotFound The invoice id provided doesn't exist + +swagger:response getInvoicesByResellerNotFound +*/ +type GetInvoicesByResellerNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetInvoicesByResellerNotFound creates GetInvoicesByResellerNotFound with default headers values +func NewGetInvoicesByResellerNotFound() *GetInvoicesByResellerNotFound { + + return &GetInvoicesByResellerNotFound{} +} + +// WithPayload adds the payload to the get invoices by reseller not found response +func (o *GetInvoicesByResellerNotFound) WithPayload(payload *models.ErrorResponse) *GetInvoicesByResellerNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoices by reseller not found response +func (o *GetInvoicesByResellerNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoicesByResellerNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetInvoicesByResellerInternalServerErrorCode is the HTTP code returned for type GetInvoicesByResellerInternalServerError +const GetInvoicesByResellerInternalServerErrorCode int = 500 + +/*GetInvoicesByResellerInternalServerError Something unexpected happend, error raised + +swagger:response getInvoicesByResellerInternalServerError +*/ +type GetInvoicesByResellerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetInvoicesByResellerInternalServerError creates GetInvoicesByResellerInternalServerError with default headers values +func NewGetInvoicesByResellerInternalServerError() *GetInvoicesByResellerInternalServerError { + + return &GetInvoicesByResellerInternalServerError{} +} + +// WithPayload adds the payload to the get invoices by reseller internal server error response +func (o *GetInvoicesByResellerInternalServerError) WithPayload(payload *models.ErrorResponse) *GetInvoicesByResellerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get invoices by reseller internal server error response +func (o *GetInvoicesByResellerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetInvoicesByResellerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_urlbuilder.go b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_urlbuilder.go new file mode 100644 index 0000000..4e88361 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/get_invoices_by_reseller_urlbuilder.go @@ -0,0 +1,115 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// GetInvoicesByResellerURL generates an URL for the get invoices by reseller operation +type GetInvoicesByResellerURL struct { + ID string + + Months *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetInvoicesByResellerURL) WithBasePath(bp string) *GetInvoicesByResellerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetInvoicesByResellerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetInvoicesByResellerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice/reseller/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetInvoicesByResellerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var monthsQ string + if o.Months != nil { + monthsQ = swag.FormatInt64(*o.Months) + } + if monthsQ != "" { + qs.Set("months", monthsQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetInvoicesByResellerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetInvoicesByResellerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetInvoicesByResellerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetInvoicesByResellerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetInvoicesByResellerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetInvoicesByResellerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/list_customer_invoices.go b/services/billing/restapi/operations/invoice_management/list_customer_invoices.go new file mode 100644 index 0000000..2899112 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_customer_invoices.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListCustomerInvoicesHandlerFunc turns a function with the right signature into a list customer invoices handler +type ListCustomerInvoicesHandlerFunc func(ListCustomerInvoicesParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListCustomerInvoicesHandlerFunc) Handle(params ListCustomerInvoicesParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListCustomerInvoicesHandler interface for that can handle valid list customer invoices params +type ListCustomerInvoicesHandler interface { + Handle(ListCustomerInvoicesParams, interface{}) middleware.Responder +} + +// NewListCustomerInvoices creates a new http.Handler for the list customer invoices operation +func NewListCustomerInvoices(ctx *middleware.Context, handler ListCustomerInvoicesHandler) *ListCustomerInvoices { + return &ListCustomerInvoices{Context: ctx, Handler: handler} +} + +/*ListCustomerInvoices swagger:route GET /invoice/customer invoiceManagement listCustomerInvoices + +Retrieve customers' invoices + +*/ +type ListCustomerInvoices struct { + Context *middleware.Context + Handler ListCustomerInvoicesHandler +} + +func (o *ListCustomerInvoices) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListCustomerInvoicesParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/list_customer_invoices_parameters.go b/services/billing/restapi/operations/invoice_management/list_customer_invoices_parameters.go new file mode 100644 index 0000000..5d9f783 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_customer_invoices_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListCustomerInvoicesParams creates a new ListCustomerInvoicesParams object +// no default values defined in spec. +func NewListCustomerInvoicesParams() ListCustomerInvoicesParams { + + return ListCustomerInvoicesParams{} +} + +// ListCustomerInvoicesParams contains all the bound params for the list customer invoices operation +// typically these are obtained from a http.Request +// +// swagger:parameters ListCustomerInvoices +type ListCustomerInvoicesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListCustomerInvoicesParams() beforehand. +func (o *ListCustomerInvoicesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/list_customer_invoices_responses.go b/services/billing/restapi/operations/invoice_management/list_customer_invoices_responses.go new file mode 100644 index 0000000..cd78916 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_customer_invoices_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListCustomerInvoicesOKCode is the HTTP code returned for type ListCustomerInvoicesOK +const ListCustomerInvoicesOKCode int = 200 + +/*ListCustomerInvoicesOK Description of a successfully operation + +swagger:response listCustomerInvoicesOK +*/ +type ListCustomerInvoicesOK struct { + + /* + In: Body + */ + Payload []*models.Invoice `json:"body,omitempty"` +} + +// NewListCustomerInvoicesOK creates ListCustomerInvoicesOK with default headers values +func NewListCustomerInvoicesOK() *ListCustomerInvoicesOK { + + return &ListCustomerInvoicesOK{} +} + +// WithPayload adds the payload to the list customer invoices o k response +func (o *ListCustomerInvoicesOK) WithPayload(payload []*models.Invoice) *ListCustomerInvoicesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list customer invoices o k response +func (o *ListCustomerInvoicesOK) SetPayload(payload []*models.Invoice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCustomerInvoicesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Invoice, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListCustomerInvoicesInternalServerErrorCode is the HTTP code returned for type ListCustomerInvoicesInternalServerError +const ListCustomerInvoicesInternalServerErrorCode int = 500 + +/*ListCustomerInvoicesInternalServerError Something unexpected happend, error raised + +swagger:response listCustomerInvoicesInternalServerError +*/ +type ListCustomerInvoicesInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListCustomerInvoicesInternalServerError creates ListCustomerInvoicesInternalServerError with default headers values +func NewListCustomerInvoicesInternalServerError() *ListCustomerInvoicesInternalServerError { + + return &ListCustomerInvoicesInternalServerError{} +} + +// WithPayload adds the payload to the list customer invoices internal server error response +func (o *ListCustomerInvoicesInternalServerError) WithPayload(payload *models.ErrorResponse) *ListCustomerInvoicesInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list customer invoices internal server error response +func (o *ListCustomerInvoicesInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCustomerInvoicesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/list_customer_invoices_urlbuilder.go b/services/billing/restapi/operations/invoice_management/list_customer_invoices_urlbuilder.go new file mode 100644 index 0000000..b6a17b0 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_customer_invoices_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListCustomerInvoicesURL generates an URL for the list customer invoices operation +type ListCustomerInvoicesURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCustomerInvoicesURL) WithBasePath(bp string) *ListCustomerInvoicesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCustomerInvoicesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListCustomerInvoicesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice/customer" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListCustomerInvoicesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListCustomerInvoicesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListCustomerInvoicesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListCustomerInvoicesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListCustomerInvoicesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListCustomerInvoicesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/list_invoices.go b/services/billing/restapi/operations/invoice_management/list_invoices.go new file mode 100644 index 0000000..8eb714a --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_invoices.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListInvoicesHandlerFunc turns a function with the right signature into a list invoices handler +type ListInvoicesHandlerFunc func(ListInvoicesParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListInvoicesHandlerFunc) Handle(params ListInvoicesParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListInvoicesHandler interface for that can handle valid list invoices params +type ListInvoicesHandler interface { + Handle(ListInvoicesParams, interface{}) middleware.Responder +} + +// NewListInvoices creates a new http.Handler for the list invoices operation +func NewListInvoices(ctx *middleware.Context, handler ListInvoicesHandler) *ListInvoices { + return &ListInvoices{Context: ctx, Handler: handler} +} + +/*ListInvoices swagger:route GET /invoice invoiceManagement listInvoices + +Summary for this endpoint + +*/ +type ListInvoices struct { + Context *middleware.Context + Handler ListInvoicesHandler +} + +func (o *ListInvoices) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListInvoicesParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/list_invoices_parameters.go b/services/billing/restapi/operations/invoice_management/list_invoices_parameters.go new file mode 100644 index 0000000..5c42a81 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_invoices_parameters.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// NewListInvoicesParams creates a new ListInvoicesParams object +// no default values defined in spec. +func NewListInvoicesParams() ListInvoicesParams { + + return ListInvoicesParams{} +} + +// ListInvoicesParams contains all the bound params for the list invoices operation +// typically these are obtained from a http.Request +// +// swagger:parameters ListInvoices +type ListInvoicesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Invoice model partially filled to use for the filtering of the invoices + In: body + */ + Model *models.Invoice +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListInvoicesParams() beforehand. +func (o *ListInvoicesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Invoice + if err := route.Consumer.Consume(r.Body, &body); err != nil { + res = append(res, errors.NewParseError("model", "body", "", err)) + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Model = &body + } + } + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/list_invoices_responses.go b/services/billing/restapi/operations/invoice_management/list_invoices_responses.go new file mode 100644 index 0000000..01baee6 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_invoices_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListInvoicesOKCode is the HTTP code returned for type ListInvoicesOK +const ListInvoicesOKCode int = 200 + +/*ListInvoicesOK Description of a successfully operation + +swagger:response listInvoicesOK +*/ +type ListInvoicesOK struct { + + /* + In: Body + */ + Payload []*models.Invoice `json:"body,omitempty"` +} + +// NewListInvoicesOK creates ListInvoicesOK with default headers values +func NewListInvoicesOK() *ListInvoicesOK { + + return &ListInvoicesOK{} +} + +// WithPayload adds the payload to the list invoices o k response +func (o *ListInvoicesOK) WithPayload(payload []*models.Invoice) *ListInvoicesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list invoices o k response +func (o *ListInvoicesOK) SetPayload(payload []*models.Invoice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListInvoicesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Invoice, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListInvoicesInternalServerErrorCode is the HTTP code returned for type ListInvoicesInternalServerError +const ListInvoicesInternalServerErrorCode int = 500 + +/*ListInvoicesInternalServerError Something unexpected happend, error raised + +swagger:response listInvoicesInternalServerError +*/ +type ListInvoicesInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListInvoicesInternalServerError creates ListInvoicesInternalServerError with default headers values +func NewListInvoicesInternalServerError() *ListInvoicesInternalServerError { + + return &ListInvoicesInternalServerError{} +} + +// WithPayload adds the payload to the list invoices internal server error response +func (o *ListInvoicesInternalServerError) WithPayload(payload *models.ErrorResponse) *ListInvoicesInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list invoices internal server error response +func (o *ListInvoicesInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListInvoicesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/list_invoices_urlbuilder.go b/services/billing/restapi/operations/invoice_management/list_invoices_urlbuilder.go new file mode 100644 index 0000000..c8d0b8c --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_invoices_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListInvoicesURL generates an URL for the list invoices operation +type ListInvoicesURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListInvoicesURL) WithBasePath(bp string) *ListInvoicesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListInvoicesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListInvoicesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListInvoicesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListInvoicesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListInvoicesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListInvoicesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListInvoicesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListInvoicesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/invoice_management/list_reseller_invoices.go b/services/billing/restapi/operations/invoice_management/list_reseller_invoices.go new file mode 100644 index 0000000..d6f53ed --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_reseller_invoices.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListResellerInvoicesHandlerFunc turns a function with the right signature into a list reseller invoices handler +type ListResellerInvoicesHandlerFunc func(ListResellerInvoicesParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListResellerInvoicesHandlerFunc) Handle(params ListResellerInvoicesParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListResellerInvoicesHandler interface for that can handle valid list reseller invoices params +type ListResellerInvoicesHandler interface { + Handle(ListResellerInvoicesParams, interface{}) middleware.Responder +} + +// NewListResellerInvoices creates a new http.Handler for the list reseller invoices operation +func NewListResellerInvoices(ctx *middleware.Context, handler ListResellerInvoicesHandler) *ListResellerInvoices { + return &ListResellerInvoices{Context: ctx, Handler: handler} +} + +/*ListResellerInvoices swagger:route GET /invoice/reseller invoiceManagement listResellerInvoices + +Retrieve resellers' invoices + +*/ +type ListResellerInvoices struct { + Context *middleware.Context + Handler ListResellerInvoicesHandler +} + +func (o *ListResellerInvoices) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListResellerInvoicesParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/invoice_management/list_reseller_invoices_parameters.go b/services/billing/restapi/operations/invoice_management/list_reseller_invoices_parameters.go new file mode 100644 index 0000000..f6b0a44 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_reseller_invoices_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListResellerInvoicesParams creates a new ListResellerInvoicesParams object +// no default values defined in spec. +func NewListResellerInvoicesParams() ListResellerInvoicesParams { + + return ListResellerInvoicesParams{} +} + +// ListResellerInvoicesParams contains all the bound params for the list reseller invoices operation +// typically these are obtained from a http.Request +// +// swagger:parameters ListResellerInvoices +type ListResellerInvoicesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListResellerInvoicesParams() beforehand. +func (o *ListResellerInvoicesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/restapi/operations/invoice_management/list_reseller_invoices_responses.go b/services/billing/restapi/operations/invoice_management/list_reseller_invoices_responses.go new file mode 100644 index 0000000..87cfee0 --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_reseller_invoices_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ListResellerInvoicesOKCode is the HTTP code returned for type ListResellerInvoicesOK +const ListResellerInvoicesOKCode int = 200 + +/*ListResellerInvoicesOK Description of a successfully operation + +swagger:response listResellerInvoicesOK +*/ +type ListResellerInvoicesOK struct { + + /* + In: Body + */ + Payload []*models.Invoice `json:"body,omitempty"` +} + +// NewListResellerInvoicesOK creates ListResellerInvoicesOK with default headers values +func NewListResellerInvoicesOK() *ListResellerInvoicesOK { + + return &ListResellerInvoicesOK{} +} + +// WithPayload adds the payload to the list reseller invoices o k response +func (o *ListResellerInvoicesOK) WithPayload(payload []*models.Invoice) *ListResellerInvoicesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list reseller invoices o k response +func (o *ListResellerInvoicesOK) SetPayload(payload []*models.Invoice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListResellerInvoicesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Invoice, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListResellerInvoicesInternalServerErrorCode is the HTTP code returned for type ListResellerInvoicesInternalServerError +const ListResellerInvoicesInternalServerErrorCode int = 500 + +/*ListResellerInvoicesInternalServerError Something unexpected happend, error raised + +swagger:response listResellerInvoicesInternalServerError +*/ +type ListResellerInvoicesInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListResellerInvoicesInternalServerError creates ListResellerInvoicesInternalServerError with default headers values +func NewListResellerInvoicesInternalServerError() *ListResellerInvoicesInternalServerError { + + return &ListResellerInvoicesInternalServerError{} +} + +// WithPayload adds the payload to the list reseller invoices internal server error response +func (o *ListResellerInvoicesInternalServerError) WithPayload(payload *models.ErrorResponse) *ListResellerInvoicesInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list reseller invoices internal server error response +func (o *ListResellerInvoicesInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListResellerInvoicesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/invoice_management/list_reseller_invoices_urlbuilder.go b/services/billing/restapi/operations/invoice_management/list_reseller_invoices_urlbuilder.go new file mode 100644 index 0000000..eb4fb6f --- /dev/null +++ b/services/billing/restapi/operations/invoice_management/list_reseller_invoices_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package invoice_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListResellerInvoicesURL generates an URL for the list reseller invoices operation +type ListResellerInvoicesURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListResellerInvoicesURL) WithBasePath(bp string) *ListResellerInvoicesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListResellerInvoicesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListResellerInvoicesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/invoice/reseller" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListResellerInvoicesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListResellerInvoicesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListResellerInvoicesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListResellerInvoicesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListResellerInvoicesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListResellerInvoicesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/status_management/get_status.go b/services/billing/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/services/billing/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/status_management/get_status_parameters.go b/services/billing/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..f5c0184 --- /dev/null +++ b/services/billing/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the endpoint to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"kafka-receiver", "kafka-sender", "status", "trigger", "bulk", "invoice"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/billing/restapi/operations/status_management/get_status_responses.go b/services/billing/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..2566942 --- /dev/null +++ b/services/billing/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/status_management/get_status_urlbuilder.go b/services/billing/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..151ece5 --- /dev/null +++ b/services/billing/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/status_management/show_status.go b/services/billing/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/services/billing/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/status_management/show_status_parameters.go b/services/billing/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/services/billing/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/billing/restapi/operations/status_management/show_status_responses.go b/services/billing/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..24c77c7 --- /dev/null +++ b/services/billing/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/status_management/show_status_urlbuilder.go b/services/billing/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..6efc165 --- /dev/null +++ b/services/billing/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/operations/trigger_management/periodic_run.go b/services/billing/restapi/operations/trigger_management/periodic_run.go new file mode 100644 index 0000000..3f81fdc --- /dev/null +++ b/services/billing/restapi/operations/trigger_management/periodic_run.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// PeriodicRunHandlerFunc turns a function with the right signature into a periodic run handler +type PeriodicRunHandlerFunc func(PeriodicRunParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn PeriodicRunHandlerFunc) Handle(params PeriodicRunParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// PeriodicRunHandler interface for that can handle valid periodic run params +type PeriodicRunHandler interface { + Handle(PeriodicRunParams, interface{}) middleware.Responder +} + +// NewPeriodicRun creates a new http.Handler for the periodic run operation +func NewPeriodicRun(ctx *middleware.Context, handler PeriodicRunHandler) *PeriodicRun { + return &PeriodicRun{Context: ctx, Handler: handler} +} + +/*PeriodicRun swagger:route GET /trigger/periodicrun triggerManagement periodicRun + +Periodic run of the bulk generation of invoices + +*/ +type PeriodicRun struct { + Context *middleware.Context + Handler PeriodicRunHandler +} + +func (o *PeriodicRun) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewPeriodicRunParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/billing/restapi/operations/trigger_management/periodic_run_parameters.go b/services/billing/restapi/operations/trigger_management/periodic_run_parameters.go new file mode 100644 index 0000000..179132d --- /dev/null +++ b/services/billing/restapi/operations/trigger_management/periodic_run_parameters.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewPeriodicRunParams creates a new PeriodicRunParams object +// no default values defined in spec. +func NewPeriodicRunParams() PeriodicRunParams { + + return PeriodicRunParams{} +} + +// PeriodicRunParams contains all the bound params for the periodic run operation +// typically these are obtained from a http.Request +// +// swagger:parameters periodicRun +type PeriodicRunParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime to override the time.now() to simulate other days + In: query + */ + Today *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewPeriodicRunParams() beforehand. +func (o *PeriodicRunParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qToday, qhkToday, _ := qs.GetOK("today") + if err := o.bindToday(qToday, qhkToday, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindToday binds and validates parameter Today from query. +func (o *PeriodicRunParams) bindToday(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("today", "query", "strfmt.DateTime", raw) + } + o.Today = (value.(*strfmt.DateTime)) + + if err := o.validateToday(formats); err != nil { + return err + } + + return nil +} + +// validateToday carries on validations for parameter Today +func (o *PeriodicRunParams) validateToday(formats strfmt.Registry) error { + + if err := validate.FormatOf("today", "query", "datetime", o.Today.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/billing/restapi/operations/trigger_management/periodic_run_responses.go b/services/billing/restapi/operations/trigger_management/periodic_run_responses.go new file mode 100644 index 0000000..ce5c07a --- /dev/null +++ b/services/billing/restapi/operations/trigger_management/periodic_run_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" +) + +// PeriodicRunAcceptedCode is the HTTP code returned for type PeriodicRunAccepted +const PeriodicRunAcceptedCode int = 202 + +/*PeriodicRunAccepted The request for processing the periodic run had been added to the queue + +swagger:response periodicRunAccepted +*/ +type PeriodicRunAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewPeriodicRunAccepted creates PeriodicRunAccepted with default headers values +func NewPeriodicRunAccepted() *PeriodicRunAccepted { + + return &PeriodicRunAccepted{} +} + +// WithPayload adds the payload to the periodic run accepted response +func (o *PeriodicRunAccepted) WithPayload(payload *models.ItemCreatedResponse) *PeriodicRunAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the periodic run accepted response +func (o *PeriodicRunAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *PeriodicRunAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/billing/restapi/operations/trigger_management/periodic_run_urlbuilder.go b/services/billing/restapi/operations/trigger_management/periodic_run_urlbuilder.go new file mode 100644 index 0000000..b4ea3a8 --- /dev/null +++ b/services/billing/restapi/operations/trigger_management/periodic_run_urlbuilder.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/strfmt" +) + +// PeriodicRunURL generates an URL for the periodic run operation +type PeriodicRunURL struct { + Today *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *PeriodicRunURL) WithBasePath(bp string) *PeriodicRunURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *PeriodicRunURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *PeriodicRunURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/periodicrun" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var todayQ string + if o.Today != nil { + todayQ = o.Today.String() + } + if todayQ != "" { + qs.Set("today", todayQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *PeriodicRunURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *PeriodicRunURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *PeriodicRunURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on PeriodicRunURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on PeriodicRunURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *PeriodicRunURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/billing/restapi/server.go b/services/billing/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/services/billing/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/services/billing/run/cert.crt b/services/billing/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/billing/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/billing/run/config.toml b/services/billing/run/config.toml new file mode 100644 index 0000000..02471c1 --- /dev/null +++ b/services/billing/run/config.toml @@ -0,0 +1,98 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "24h" +DBName = "cyclops" +Host = "localhost" +Password = "pass1234" +Port = 5432 +# SSLMode = enable | disable +SSLMode = "disable" +UserName = "cyclops" + +[EVENTS] +Filters = [ "filter1", "filter2", "filter3" ] + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +# "" for no file-logging +LogFile = "./SERVICE.log" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8000" +CDR = "cdr:8000" +CreditSystem = "creditsystem:8000" +CustomerDB = "customerdb:8000" +EventsEngine = "eventsengine:8000" +PlanManager = "planmanager:8000" +UDR = "udr:8000" + +[KAFKA] +Brokers = [ "kafka1:9092", "kafka2:9093", "kafka3:9094" ] +CDRIn = [ "CDR" ] +CDROut = [ "Credit" ] +Credit-SystemIn = [ "Credit" ] +EventsEngineIn = [ "Events" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMin = 10e3 +SizeMax = 10e6 +UDRIn = [ "UDR" ] +UDROut = [ "CDR" ] + +[KEYCLOAK] +ClientID = "CyclopsDeploy" +ClientSecret = "00000000-0000-0000-0000-000000000000" +Enabled = true +Host = "keycloak" +Port = 8000 +Realm = "Development" +RedirectURL = "" +UseHttp = true + +[PLANS] +Default = "-1" +Education = "-2" + +[PROMETHEUS] +Host = "prometheus:9090" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" diff --git a/services/billing/run/docker-compose.yml b/services/billing/run/docker-compose.yml new file mode 100644 index 0000000..8a6e52e --- /dev/null +++ b/services/billing/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: SERVICE:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/services/billing/run/key.key b/services/billing/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/billing/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/billing/server/bulkManager/bulkManager.go b/services/billing/server/bulkManager/bulkManager.go new file mode 100644 index 0000000..7043b5b --- /dev/null +++ b/services/billing/server/bulkManager/bulkManager.go @@ -0,0 +1,326 @@ +package bulkManager + +import ( + "context" + "net/http" + "strings" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/bulk_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// BulkManager is the struct defined to group and contain all the methods +// that interact with the bulk subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type BulkManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct BulkManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// Returns: +// - BulkManager: struct to interact with BulkManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *BulkManager { + + l.Trace.Printf("[BulkManager] Generating new bulkManager.\n") + + monit.InitEndpoint("bulk") + + return &BulkManager{ + db: db, + monit: monit, + } + +} + +func (m *BulkManager) getToken(param *http.Request) (token string) { + + if len(param.Header.Get("Authorization")) > 0 { + + token = strings.Fields(param.Header.Get("Authorization"))[1] + + } + + return + +} + +// GenerateInvoiceForCustomer (Swagger func) is the function behind +// GetBillRun (Swagger func) is the function behind the (GET) endpoint +// /billrun/{id} +// Its job is to provide the requested billruns from the system. +func (m *BulkManager) GetBillRun(ctx context.Context, params bulk_management.GetBillRunParams) middleware.Responder { + + l.Trace.Printf("[BulkManager] GetBillRun endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bulk", callTime) + + object, e := m.db.GetBillRun(params.ID) + + if e != nil { + + s := "Problem while retrieving the Billrun from the db: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/billrun/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewGetBillRunInternalServerError().WithPayload(&errorReturn) + + } + + if object != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/billrun/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewGetBillRunOK().WithPayload(object) + + } + + s := "The Billrun doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/billrun/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewGetBillRunNotFound().WithPayload(&missingReturn) + +} + +// ListBillRuns (Swagger func) is the function behind the (GET) endpoint +// /billrun +// Its job is to provide a list of all the billruns currently in the system. +func (m *BulkManager) ListBillRuns(ctx context.Context, params bulk_management.ListBillRunsParams) middleware.Responder { + + l.Trace.Printf("[BulkManager] ListBillRuns endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bulk", callTime) + + object, e := m.db.ListBillRuns(params.Months) + + if e != nil { + + s := "Problem while retrieving the Billruns from the db: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/billrun"}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewListBillRunsInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/billrun"}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewListBillRunsOK().WithPayload(object) + +} + +// ListBillRunsByOrganization (Swagger func) is the function behind the (GET) +// endpoint /billrun/organization/{id} +// Its job is to provide a list of all the billruns currently in the system +// linked to the provided organization. +func (m *BulkManager) ListBillRunsByOrganization(ctx context.Context, params bulk_management.ListBillRunsByOrganizationParams) middleware.Responder { + + l.Trace.Printf("[BulkManager] ListBillRuns endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bulk", callTime) + + token := m.getToken(params.HTTPRequest) + + object, e := m.db.ListBillRunsByOrganization(params.ID, token, params.Months) + + if e != nil { + + s := "Problem while retrieving the Billruns from the db: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/billrun/organization/" + params.ID}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewListBillRunsByOrganizationInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/billrun/organization/" + params.ID}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewListBillRunsByOrganizationOK().WithPayload(object) + +} + +// ReRunAllBillRuns (Swagger func) is the function behind the (PUT) endpoint +// ReRunAllBillRuns (Swagger func) is the function behind the (PUT) endpoint +// /billrun +// Its job is to re-run all the billruns currently not completed in the system. +func (m *BulkManager) ReRunAllBillRuns(ctx context.Context, params bulk_management.ReRunAllBillRunsParams) middleware.Responder { + + l.Trace.Printf("[BulkManager] ReRunAllBillRuns endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bulk", callTime) + + token := m.getToken(params.HTTPRequest) + + state, e := m.db.ReRunBillRun("", params.Months, token) + + if e != nil { + + s := "Problems while trying to re-run the not finished Billruns: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/billrun"}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunAllBillRunsInternalServerError().WithPayload(&errorReturn) + + } + + if state == dbManager.StatusMissing { + + s := "The Billrun doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/billrun"}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunAllBillRunsNotFound().WithPayload(&missingReturn) + + } + + if state == dbManager.StatusOK { + + acceptedReturn := models.ItemCreatedResponse{ + Message: "The request has been added to the queue", + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "PUT", "route": "/billrun"}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunAllBillRunsAccepted().WithPayload(&acceptedReturn) + + } + + s := "This point shouldn't had been reached, contact Diego. Previous error: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/billrun"}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunAllBillRunsInternalServerError().WithPayload(&errorReturn) + +} + +// ReRunBillRun (Swagger func) is the function behind the (PUT) endpoint +// /billrun/{id} +// Its job is to rerun the provided billrun currently not completed in the system. +func (m *BulkManager) ReRunBillRun(ctx context.Context, params bulk_management.ReRunBillRunParams) middleware.Responder { + + l.Trace.Printf("[BulkManager] ReRunBillRun endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bulk", callTime) + + token := m.getToken(params.HTTPRequest) + + state, e := m.db.ReRunBillRun(params.ID, nil, token) + + if e != nil { + + s := "Problem while trying to re-run the not finished Billrun: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/billrun/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunBillRunInternalServerError().WithPayload(&errorReturn) + + } + + if state == dbManager.StatusMissing { + + s := "The Billrun doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/billrun/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunBillRunNotFound().WithPayload(&missingReturn) + + } + + if state == dbManager.StatusOK { + + acceptedReturn := models.ItemCreatedResponse{ + Message: "The request has been added to the queue", + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "PUT", "route": "/billrun/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunBillRunAccepted().WithPayload(&acceptedReturn) + + } + + s := "This point shouldn't had been reached, contact Diego. Previous error: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/billrun/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("bulk", callTime) + + return bulk_management.NewReRunBillRunInternalServerError().WithPayload(&errorReturn) + +} diff --git a/services/billing/server/cache.go b/services/billing/server/cache.go new file mode 100644 index 0000000..bd76a69 --- /dev/null +++ b/services/billing/server/cache.go @@ -0,0 +1,553 @@ +package main + +import ( + "context" + "net/url" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/cacheManager" + cdrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client" + cdrUsage "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/usage_management" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + cusCustomer "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/customer_management" + cusProduct "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/product_management" + cusReseller "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/reseller_management" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + pmBundle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/bundle_management" + pmCycle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/cycle_management" + pmPlan "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/plan_management" + pmSku "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/sku_management" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheStart handles the initialization of the cache mechanism service. +// Returns: +// - A cacheManager reference struct already initialized and ready to be used. +func cacheStart(metrics *prometheus.GaugeVec) *cacheManager.CacheManager { + + l.Trace.Printf("[CACHE][INIT] Intializing cache mechanism.\n") + + cacheDuration, _ := time.ParseDuration(cfg.DB.CacheRetention) + + c := cacheManager.New(metrics, cacheDuration, cfg.APIKey.Token) + + resellerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusReseller.NewGetResellerParams().WithID(i) + + r, e := client.ResellerManagement.GetReseller(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the reseller with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusReseller.NewListResellersParams() + + r, e := client.ResellerManagement.ListResellers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of resellers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + customerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusCustomer.NewGetCustomerParams().WithID(i) + + r, e := client.CustomerManagement.GetCustomer(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the customer with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusCustomer.NewListCustomersParams() + + r, e := client.CustomerManagement.ListCustomers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of customers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + productFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusProduct.NewGetProductParams().WithID(i) + + r, e := client.ProductManagement.GetProduct(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the product with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusProduct.NewListProductsParams() + + r, e := client.ProductManagement.ListProducts(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of products. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + // id == id0[,id1,...,idN]?from?to + cdrFunction := func(id interface{}, token string) (interface{}, error) { + + config := cdrClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["cdr"], + Path: cdrClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + idSplit := strings.SplitN(id.(string), "?", 3) + + i := idSplit[0] + + from, e := time.Parse(time.RFC3339Nano, idSplit[1]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[1], e) + + return nil, e + + } + + f := (strfmt.DateTime)(from) + + to, e := time.Parse(time.RFC3339Nano, idSplit[2]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[2], e) + + return nil, e + + } + + t := (strfmt.DateTime)(to) + + client := cdrClient.New(config) + ctx := context.Background() + + if strings.Contains(i, ",") { + + params := cdrUsage.NewGetSystemUsageParams().WithIdlist(&i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + if i != "ALL" { + + params := cdrUsage.NewGetUsageParams().WithID(i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving the CDRs under the id [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := cdrUsage.NewGetSystemUsageParams().WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + skuFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmSku.NewGetSkuParams().WithID(id.(string)) + + r, e := client.SkuManagement.GetSku(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the sku [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := pmSku.NewListSkusParams() + + r, e := client.SkuManagement.ListSkus(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the skus list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + planFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + var planID string + + if i, exists := cfg.DefaultPlans[strings.ToLower(id.(string))]; exists { + + planID = i + + } else { + + planID = id.(string) + + } + + params := pmPlan.NewGetCompletePlanParams().WithID(planID) + + r, e := client.PlanManagement.GetCompletePlan(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmPlan.NewListCompletePlansParams() + + r, e := client.PlanManagement.ListCompletePlans(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + bundleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmBundle.NewGetSkuBundleParams().WithID(id.(string)) + + r, e := client.BundleManagement.GetSkuBundle(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmBundle.NewListSkuBundlesParams() + + r, e := client.BundleManagement.ListSkuBundles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + cycleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + var params *pmCycle.ListCyclesParams + + if id.(string) == "ALL" { + + params = pmCycle.NewListCyclesParams() + + } else { + + ty := id.(string) + + params = pmCycle.NewListCyclesParams().WithType(&ty) + + } + + r, e := client.CycleManagement.ListCycles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CYCLE-FUNCTION] There was a problem while retrieving the cycle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + c.Add("reseller", resellerFunction) + l.Trace.Printf("[CACHE][INIT] Reseller fetcher added to the cache.\n") + + c.Add("customer", customerFunction) + l.Trace.Printf("[CACHE][INIT] Customer fetcher added to the cache.\n") + + c.Add("product", productFunction) + l.Trace.Printf("[CACHE][INIT] Product fetcher added to the cache.\n") + + c.Add("cdr", cdrFunction) + l.Trace.Printf("[CACHE][INIT] CDR usage fetcher added to the cache.\n") + + c.Add("sku", skuFunction) + l.Trace.Printf("[CACHE][INIT] SKU fetcher added to the cache.\n") + + c.Add("plan", planFunction) + l.Trace.Printf("[CACHE][INIT] Plan fetcher added to the cache.\n") + + c.Add("bundle", bundleFunction) + l.Trace.Printf("[CACHE][INIT] SkuBundle fetcher added to the cache.\n") + + c.Add("cycle", cycleFunction) + l.Trace.Printf("[CACHE][INIT] Life Cycle fetcher added to the cache.\n") + + return c + +} diff --git a/services/billing/server/cacheManager/cacheManager.go b/services/billing/server/cacheManager/cacheManager.go new file mode 100644 index 0000000..ef0cf31 --- /dev/null +++ b/services/billing/server/cacheManager/cacheManager.go @@ -0,0 +1,281 @@ +package cacheManager + +import ( + "fmt" + "strings" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheFetchFunction it will need the id to retrieve and as and option a Bearer +// Keycloak token can be provided when called. +// It shall return the object and errors in case of problems. +type cacheFetchFunction func(interface{}, string) (interface{}, error) + +// cache struct is the main "object" which handles the cache and its items. +// It also contains a map with the conversions of interfaces to strings. +type cache struct { + ////conversionDictionary map[string]string + data map[string]*cacheItem + fetchers map[string]cacheFetchFunction + mutex sync.RWMutex +} + +// cacheItem struct referes to the data of each element saved in the cache. +type cacheItem struct { + fetcher cacheFetchFunction + lastUpdate time.Time + value interface{} +} + +// CacheManager is the struct defined to group and contain all the methods +// that interact with the caching mechanism. +type CacheManager struct { + APIKey string + duration time.Duration + metrics *prometheus.GaugeVec + store cache +} + +// New is the function to create the struct CacheManager. +// Parameters: +// - t: a time.Duration with the max duration alive of the cache elements. +// - k: string containing the APIKey/token in case of need. +// Returns: +// - CacheManager: struct to interact with CacheManager subsystem functionalities. +func New(metrics *prometheus.GaugeVec, t time.Duration, k string) *CacheManager { + + l.Trace.Printf("[CACHE] Initializing the cache service.\n") + + c := CacheManager{ + APIKey: k, + duration: t, + metrics: metrics, + store: cache{ + data: make(map[string]*cacheItem), + fetchers: make(map[string]cacheFetchFunction), + }, + } + + return &c + +} + +// Add function job is to insert a new model in the cache. +// What it does is link the model with a fetching function and, if wanted, with +// a plain text name, so later in order to retrieve things from the cache they +// can be refereced either by the struct model or the plain text name. +// Paramenters: +// - plainName: a case insensitive name/alias to retrieve the data. +// - fetcher: the cacheFetchFunction used to retrieve the data. +func (c *CacheManager) Add(plainName string, fetcher cacheFetchFunction) { + + l.Trace.Printf("[CACHE] Adding a new object fetcher in the cache.\n") + + key := strings.ToUpper(plainName) + + c.store.mutex.Lock() + + c.store.fetchers[key] = fetcher + + c.store.mutex.Unlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Models in Cache"}).Inc() + + return + +} + +// fetch function job is to retrieve a new and updated copy of the remote object. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) fetch(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + c.store.mutex.RLock() + + object := c.store.data[item] + + c.store.mutex.RUnlock() + + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := object.fetcher(id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + object.value = uValue + object.lastUpdate = time.Now() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// fetch function job is to create the new item in the cache and retrieve a new +// and updated initial copy of the remote object to be saved in the cache. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) init(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + key := strings.Split(item, "-")[0] + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := c.store.fetchers[key](id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + i := cacheItem{ + fetcher: c.store.fetchers[key], + lastUpdate: time.Now(), + value: uValue, + } + + c.store.mutex.Lock() + + c.store.data[item] = &i + + c.store.mutex.Unlock() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// key is a function to ensure that the creation of the the item key for the +// cache is consistent across all the functions. +// Paramenters: +// - id: the reference id of the object to be retrieved +// - model: the alias text used to identify the source of objects. +// Returns: +// - s: the key string +func (c *CacheManager) key(id interface{}, model string) (s string) { + + s = fmt.Sprintf("%v-%v", strings.ToUpper(model), id) + + return + +} + +// Get function job is to retrieve an object from the cache or fetch it from the +// source and upgrade the copy in the cache in case the expiration time has been +// exceeded. +// Paramenters: +// - id: the reference id of the object. +// - model: the text alias set to reference the model. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - The object associated with the request +// - An error raised in case something went wrong while retrieving the object. +func (c *CacheManager) Get(id interface{}, model string, token string) (interface{}, error) { + + l.Trace.Printf("[CACHE] Retrieving object [ %v, %v ] from the cache.\n", id, model) + + item := c.key(id, model) + + c.store.mutex.RLock() + + object, exists := c.store.data[item] + + c.store.mutex.RUnlock() + + if !exists { + + l.Trace.Printf("[CACHE] Object [ %v ] first time requested, including in the cache.\n", item) + + if e := c.init(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while adding the new item [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects cached"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects cached"}).Inc() + + return o, nil + + } + + l.Trace.Printf("[CACHE] Object [ %v ] exists in the cache.\n", item) + + c.store.mutex.RLock() + + diff := (time.Now()).Sub(c.store.data[item].lastUpdate) + + c.store.mutex.RUnlock() + + if diff <= c.duration { + + l.Trace.Printf("[CACHE] Object [ %v ] cache hasn't expired yet.\n", item) + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return object.value, nil + + } + + l.Warning.Printf("[CACHE] Object [ %v ] cache has expired. Starting the upgrade.\n", item) + + if e := c.fetch(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while fetching the updated data for the object [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects refreshed"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] updated retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects refreshed"}).Inc() + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return o, nil + +} diff --git a/services/billing/server/config.go b/services/billing/server/config.go new file mode 100644 index 0000000..4eb0cf9 --- /dev/null +++ b/services/billing/server/config.go @@ -0,0 +1,223 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + DefaultPlans map[string]string + Prometheus prometheusConfig +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type planConfig struct { + Default string +} +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("database.cacheretention"), + DbName: viper.GetString("database.dbname"), + Host: viper.GetString("database.host"), + Password: viper.GetString("database.password"), + Port: viper.GetInt("database.port"), + SSLMode: viper.GetString("database.sslmode"), + Username: viper.GetString("database.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + DefaultPlans: viper.GetStringMapString("plans"), + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/services/billing/server/dbManager/dbManager.go b/services/billing/server/dbManager/dbManager.go new file mode 100644 index 0000000..95b3e83 --- /dev/null +++ b/services/billing/server/dbManager/dbManager.go @@ -0,0 +1,2157 @@ +package dbManager + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "reflect" + "runtime" + "strings" + "sync" + "time" + + "github.com/go-openapi/strfmt" + "github.com/lib/pq" + "github.com/prometheus/client_golang/prometheus" + "gitlab.com/cyclops-utilities/datamodels" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/cacheManager" + cdrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + cusModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + pmModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +// Report status code vars +const ( + scaler = 1e9 + StatusDuplicated = iota + StatusFail + StatusMissing + StatusOK +) + +var ( + periodicity = map[string]int{"daily": 1, "weekly": 7, "bi-weekly": 15, + "monthly": 1, "bi-monthly": 2, "quarterly": 3, "semi-annually": 6, "annually": 0} + invTotal float64 + invTime float64 + preProcFailedInvoices map[strfmt.UUID]int64 +) + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// Parameters: +// - Cache: CacheManager pointer for the cache mechanism. +// - connStr: strings with the connection information to the database +// - Db: a gorm.DB pointer to the db to invoke all the db methods +type DbParameter struct { + Cache *cacheManager.CacheManager + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec + workersPool *pool +} + +type period struct { + from strfmt.DateTime + to strfmt.DateTime +} + +// Workers Pool config struct +type pool struct { + bufferSize int64 + metadata chan map[string]interface{} + poolActive bool + results chan workerResult + sync *sync.WaitGroup + workers int + mutex sync.RWMutex +} + +type workerResult struct { + amount float64 + billrun strfmt.UUID + organization string + status string +} + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization +// Returns: +// - DbParameter: struct to interact with dbManager functionalities +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + panic(err) + + } + + l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + dp.Db.AutoMigrate(tables...) + + l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + //dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NewScope(&models.TABLE).TableName() + "', 'TIMESCALE-ROW-INDEX');") + + // Workers Pool + p := pool{ + poolActive: false, + bufferSize: 100, + } + + maxProcs := runtime.GOMAXPROCS(0) + numCPU := runtime.NumCPU() + + if maxProcs < numCPU { + + p.workers = maxProcs + + } else { + + p.workers = numCPU + } + + dp.workersPool = &p + + // Counter for clean billruns + preProcFailedInvoices = make(map[strfmt.UUID]int64) + + return &dp + +} + +// createBillRun job is to create the skeleton of a new billrun in the system +// and provide its ID. +// Parameters: +// - size: int64 indicating the amount of invoices to be generated during the +// execution of the billrun. +// Returns: +// - id: a UUID string with the associated ID to the just created billrun. +// - e in case of any error happening. +func (d *DbParameter) createBillRun(size int64, executionType string) (id strfmt.UUID, e error) { + + l.Trace.Printf("[DB] Attempting to create a new billrun.\n") + + var o, origin models.BillRun + + status := "QUEUED" + + o = models.BillRun{ + CreationTimestamp: (strfmt.DateTime)(time.Now()), + InvoicesCount: size, + Status: &status, + ExecutionType: executionType, + } + + if r := d.Db.Where(&o).First(&origin).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + if r := d.Db.Create(&o); r.Error == nil { + + l.Info.Printf("[DB] Billrun inserted successfully.\n") + + d.Metrics["count"].With(prometheus.Labels{"type": "Billruns created"}).Inc() + + id = r.Statement.Model.(*models.BillRun).ID + + } else { + + l.Warning.Printf("[DB] Something went wrong while trying to create a new billrun in the system. Error: %v.\n", r.Error) + + e = r.Error + + } + + } else { + + l.Warning.Printf("[DB] Billrun with id [ %v ] is already in the system, check with the administrator.", origin.ID) + + id = origin.ID + e = errors.New("billrun duplication") + + } + + return + +} + +// createInvoice job is to create the skeleton of a new invoice in the system +// and provide its ID. +// Parameters: +// - p: a preiod object containing the timeframe for the invoice. +// - organization: a string contining the ID of the organization for the invoice. +// Returns: +// - id: a UUID string with the associated ID to the just created invoice. +// - e in case of any error happening. +// - +func (d *DbParameter) createInvoice(p period, organization, orgType string) (id strfmt.UUID, e error) { + + l.Trace.Printf("[DB] Attempting to create a new invoice.\n") + + var o, origin models.Invoice + + status := "NOT_PROCESSED" + + o = models.Invoice{ + Items: make(datamodels.JSONdb), + OrganizationID: organization, + OrganizationType: orgType, + PeriodEndDate: (strfmt.Date)(((time.Time)(p.to)).AddDate(0, 0, -1)), + PeriodStartDate: (strfmt.Date)(p.from), + Status: &status, + } + + if r := d.Db.Where(&o).First(&origin).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + o.GenerationTimestamp = (strfmt.DateTime)(time.Now()) + status := "UNPAID" + o.PaymentStatus = &status + o.PaymentDeadline = (strfmt.Date)(time.Now().AddDate(0, 0, 15)) + + if r := d.Db.Create(&o); r.Error == nil { + + l.Info.Printf("[DB] Invoice created successfully.\n") + + d.Metrics["count"].With(prometheus.Labels{"type": "Invoices created"}).Inc() + + id = r.Statement.Model.(*models.Invoice).ID + + } else { + + l.Warning.Printf("[DB] Something went wrong while trying to save the invoice in the system. Error: %v.\n", r.Error) + + e = r.Error + + } + + } else { + + l.Trace.Printf("[DB] Invoice with id [ %v ] is already in the system.", origin.ID) + + id = origin.ID + e = errors.New("invoice already in the system") + + } + + return + +} + +// getFloat job is to check the type of the interface and properly cast its +// value into a float64. +// Parameters: +// - i: interface that should contain a float number. +// Returns: +// - f: a float64 with the value contained in the interface provided. +func (d *DbParameter) getFloat(i interface{}) (f float64) { + + var e error + + if i == nil { + + f = float64(0) + + return + + } + + if v := reflect.ValueOf(i); v.Kind() == reflect.Float64 { + + f = i.(float64) + + } else { + + f, e = i.(json.Number).Float64() + + if e != nil { + + l.Trace.Printf("[DB] GetFloat failed to convert [ %v ]. Error: %v\n", i, e) + + } + + } + + return + +} + +// getNiceFloat job is to turn the ugly float64 provided into a "nice looking" +// one according to the scale set, so we move from a floating coma number into +// a fixed coma number. +// Parameters: +// - i: the ugly floating coma number. +// Returns: +// - o: the "nice looking" fixed coma float. +func (d *DbParameter) getNiceFloat(i float64) (o float64) { + + min := float64(float64(1) / float64(scaler)) + + if diff := math.Abs(i - min); diff < min { + + o = float64(0) + + } else { + + //o = float64(math.Round(i*scaler) / scaler) + o = float64(i) + + } + + return + +} + +// contains job is to check if the string is contiained in the StringArray. +// Paramenters: +// - slice: the StringArray to check. +// - s: the probing string. +// Returns: +// - boolean with true if is contained +func (d *DbParameter) contains(slice pq.StringArray, s string) bool { + + for _, v := range slice { + + if v == s { + + return true + + } + + } + + return false + +} + +// GetBillRun job is to retrieve from the system the BillRunReport associated +// with the provided ID. +// Parameters: +// - id: a UUID string with the associated ID to the billrun requested. +// Returns: +// - the billrunreport associated to the provided ID. +// - e in case of any error happening. +func (d *DbParameter) GetBillRun(id strfmt.UUID) (*models.BillRunReport, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the billrun [ %v ].\n", id) + + var o models.BillRunReport + var e error + var oInvoices []*models.InvoiceMetadata + + if e = d.Db.Where(&models.BillRun{ID: id}).First(&models.BillRun{}).Scan(&o).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the billrun [ %v ]. Error: %v\n", id, e) + + } else { + + if e = d.Db.Where(&models.Invoice{BillRunID: id}).Find(&([]*models.Invoice{})).Scan(&oInvoices).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the associated invoices to the billrun [ %v ]. Error: %v\n", id, e) + + } else { + + o.InvoicesList = oInvoices + + l.Debug.Printf("[DB] Billrun [ %v ] with its corresponding [ %v ] invoices retrieved from the system.\n", id, len(oInvoices)) + + } + + } + + return &o, e + +} + +// GetInvoice job is to retrieve from the system the Invoice associated with +// the provided ID. +// Parameters: +// - id: a UUID string with the associated ID to the invoice requested. +// Returns: +// - the invoice associated to the provided ID. +// - e in case of any error happening. +func (d *DbParameter) GetInvoice(id strfmt.UUID) (*models.Invoice, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the invoice [ %v ].\n", id) + + var o models.Invoice + var e error + + if e = d.Db.Where(&models.Invoice{ID: id}).First(&o).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the invoice [ %v ]. Error: %v\n", id, e) + + } else { + + l.Debug.Printf("[DB] Invoice [ %v ] retrieved from the system.\n", id) + + } + + return &o, e + +} + +// GetInvoicesByOrganization job is to retrieve from the system the existent +// invoice(s) related to the organization whose ID is provided.- +// Parameters: +// - id: a string with the organization ID associated to the invoice. +// - months: optional int64 with the amount of months to go back in time looking +// for the invoices associated. +// Returns: +// - o: slice of Invoice containend the requested invoices from the system. +// - e in case of any error happening. +func (d *DbParameter) GetInvoicesByOrganization(id string, months *int64) (o []*models.Invoice, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve the invoices from organization [ %v ].\n", id) + + m := int64(3) + + if months != nil { + + m = *months + + } + + timeWindow := d.getWindow("GenerationTimestamp", m) + + if e = d.Db.Where(timeWindow).Where(&models.Invoice{OrganizationID: id}).Find(&o).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the invoices for the organization [ %v ]. Error: %v\n", id, e) + + } else { + + l.Debug.Printf("[DB] Invoices for organization [ %v ] retrieved from the system.\n", id) + + } + + return + +} + +// getWindow job is to select the timeframe for the usage retrievals according +// to the data providad today-months NOW() - INTERVAL '%v month'", d.Db.NamingStrategy.ColumnName("", col), 3) + + } else { + + s = fmt.Sprintf("%v > NOW() - INTERVAL '%v month'", d.Db.NamingStrategy.ColumnName("", col), months) + + } + + return s + +} + +// GenerateInvoicesBy job is to start the generation of the invoice(s) linked +// with the provided organiztion. Ideally this function will only be run with +// the idea of override the period of the invoice, but the simple re-run of the +// invoice possibility is present. +// Parameters: +// - org: a string with the type of organization: reseller or customer. +// - id: a string with the organization ID whose invoice is going to be generated. +// - token: a string with an optional keycloak bearer token. +// - from: optional datetime value to override the initial time of the invoicing +// period. +// - to: optional datetime value to override the final time of the invoicing +// period. +// Returns: +// - id: a UUID string with the associated ID of billrun in charge of the +// generation of the invoices. +// - e in case of any error happening. +func (d *DbParameter) GenerateInvoicesBy(org, id, token string, from, to strfmt.DateTime) (billrunID string, e error) { + + l.Trace.Printf("[DB] Starting the generation of invoices for customer [ %v ].\n", id) + + var billrun strfmt.UUID + + billrun, e = d.createBillRun(1, "ORGANIZATION: "+id) + + billrunID = (string)(billrun) + + if e != nil { + + return + + } + + metadata := make(map[string]interface{}) + metadata[org] = id + metadata["billrun"] = billrun + metadata["regenerate"] = true + + if !((time.Time)(from)).IsZero() && !((time.Time)(to)).IsZero() { + + metadata["period"] = period{ + from: from, + to: to, + } + + } + + go d.InvoicesGeneration(metadata, token) + + return + +} + +// ListBillRuns job is to provide the list of billruns in the system, by default +// this list only goes back in time 3 months from today, but it can be overrided. +// Parameters: +// - months: optional int64 containing the amount of month to look back in time. +// Returns: +// - o: slice of BillRunList containing the billruns in the system. +// - e in case of any error happening. +func (d *DbParameter) ListBillRuns(months *int64) (o []*models.BillRunList, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the billruns in the system.\n") + + m := int64(3) + + if months != nil { + + m = *months + + } + + timeWindow := d.getWindow("CreationTimestamp", m) + + if e = d.Db.Where(timeWindow).Find(&([]*models.BillRun{})).Scan(&o).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the billruns in the system. Error: %v\n", e) + + } else { + + l.Debug.Printf("[DB] [ %v ] billruns retrieved from the system.\n", len(o)) + + } + + return + +} + +// ListBillRunsByOrganization job is to provide the list of billruns in the system +// that are linked to the specific organization. +// By default this list only goes back in time 3 months from today, but it can +// be overrided. +// Parameters: +// - months: optional int64 containing the amount of month to look back in time. +// Returns: +// - o: slice of BillRunList containing the billruns in the system. +// - e in case of any error happening. +func (d *DbParameter) ListBillRunsByOrganization(organization, token string, months *int64) (o []*models.BillRunList, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the billruns in the system linked to the organization [ %v ].\n", organization) + + var o1, o2 []*models.BillRunList + + m := int64(3) + + executionTypeCus := "ORGANIZATION: " + executionTypeRes := "ORGANIZATION: " + + c, e := d.Cache.Get(organization, "customer", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the customers. Assuming the id [ %v ] is a reseller. Error: %v\n", organization, e) + + executionTypeRes += organization + executionTypeCus = "" + + } else { + + customer := c.(cusModels.Customer) + + executionTypeRes += customer.ResellerID + executionTypeCus += organization + + } + + if months != nil { + + m = *months + + } + + timeWindow := d.getWindow("CreationTimestamp", m) + + if e1 := d.Db.Where(timeWindow).Where(&models.BillRun{ExecutionType: executionTypeCus}).Find(&([]*models.BillRun{})).Scan(&o1).Error; e1 != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the billruns in the system for [ %v ]. Error: %v\n", executionTypeCus, e1) + + e = fmt.Errorf("%v search gave problems. Error: %v", executionTypeCus, e1) + + } + + if e2 := d.Db.Where(timeWindow).Where(&models.BillRun{ExecutionType: executionTypeRes}).Find(&([]*models.BillRun{})).Scan(&o2).Error; e2 != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the billruns in the system for [ %v ]. Error: %v\n", executionTypeRes, e2) + + e = fmt.Errorf("%v search gave problems. Error: %v. Error chain: %v", executionTypeRes, e2, e) + + } + + o = append(o1, o2...) + + l.Debug.Printf("[DB] [ %v ] billruns retrieved from the system.\n", len(o)) + + return + +} + +// ListInvoices job is to provide the list of invoices saved in the system. +// It admits the use of and invoice model to filter the results. +// Parameters: +// - model: optional Invoice model with data set to be used as a filter. +// Returns: +// - o: slice of Invoice containing the invoices matching the filter in the system. +// - e in case of any error happening. +func (d *DbParameter) ListInvoices(model *models.Invoice) (o []*models.Invoice, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the invoices in the system.\n") + + if e = d.Db.Where(model).Find(&o).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the invoices from the system. Error: %v\n", e) + + } else { + + l.Debug.Printf("[DB] [ %v ] invoices retrieved from the system.\n", len(o)) + + } + + return + +} + +// getPeriods job is to generate all the possibles invoicing periods that the +// system could be able to safely generate and invoice for based on the day +// marked by today, being the default behaviour to consider today as time.Now(). +// Parameters: +// - today: an optional time.Time contained an overrider date. +// Returns: +// - periods: a map[string]period containing all the possibles periods for +// invoicing that can be used considering today as the actual day +// - e in case of any error happening. +func (d *DbParameter) getPeriods(today time.Time) (periods map[string]period) { + + l.Trace.Printf("[DB] Getting the time periods windows for the autonomous invoices.\n") + + now := time.Now() + periods = make(map[string]period) + + if !today.IsZero() { + + now = today + + } + + for id, v := range periodicity { + + var end, start time.Time + + switch id { + + case "daily": + + end = now + start = end.AddDate(0, 0, -v) + + case "weekly", "bi-weekly": + + multiplier := int(now.Weekday()) - 1 + + if multiplier < 0 { + + multiplier = 6 + + } + + end = now.AddDate(0, 0, -multiplier) + start = end.AddDate(0, 0, -v) + + case "monthly", "bi-monthly", "quarterly", "semi-annually": + + if int(now.Month()) < (v + 1) { + + month := 12 - v + 1 + + start = time.Date(now.Year()-1, time.Month(month), 1, 0, 0, 0, 0, time.UTC) + end = time.Date(now.Year(), time.Month(1), 1, 0, 0, 0, 0, time.UTC) + + } else { + + month := ((int(now.Month()) - 1) % v) * v + + start = time.Date(now.Year(), time.Month(month), 1, 0, 0, 0, 0, time.UTC) + end = time.Date(now.Year(), time.Month(month+v+1), 1, 0, 0, 0, 0, time.UTC) + + } + + case "annually": + + start = time.Date(now.Year()-1, time.Month(1), 1, 0, 0, 0, 0, time.UTC) + end = time.Date(now.Year(), time.Month(1), 1, 0, 0, 0, 0, time.UTC) + + } + + f := strfmt.DateTime(time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, time.UTC)) + t := strfmt.DateTime(time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, time.UTC)) + + periods[id] = period{from: f, to: t} + + } + + return + +} + +// InvoicesGeneration job is to initiate a billrun process. +// Specifically its function is to automatically retrieve every reseller and +// customer in the system with their corresponding linked poroducts, select the +// adecuate time for its invoice and start the pool of workers and feed it. +// It also includes the option to override several parts and be used as a way to +// re-run and/or run specific invoice generations. +// Parameters: +// - metadata: the map[string]interface channel used to send the information +// needed for the invoice generation process. +// - token: a string with an optional keycloak bearer token. +func (d *DbParameter) InvoicesGeneration(metadata map[string]interface{}, token string) { + + var today time.Time + var wg *sync.WaitGroup + var pipe chan<- map[string]interface{} + + if t, exists := metadata["today"]; exists || metadata == nil { + + l.Trace.Printf("[DB] Starting the autonomous invoice generation pre-processing.\n") + + if t != nil { + + today = (time.Time)(t.(strfmt.DateTime)) + + } + + // 1) Generate periods of time according to date and generate a billrun for each + periods := d.getPeriods(today) + + // 2) List all resellers and customers + r, e := d.Cache.Get("ALL", "reseller", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the resellers. Error: %v\n", e) + + return + + } + + resellers := r.([]*cusModels.Reseller) + + c, e := d.Cache.Get("ALL", "customer", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the customers. Error: %v\n", e) + + return + + } + + customers := c.([]*cusModels.Customer) + + // 3) Separate them by invoicing periods adding the dates from before + + resellersByPeriod := make(map[string][]string) + cdrByReseller := make(map[string][]string) + + for i := range resellers { + + if !(*resellers[i].Billable) { + + continue + + } + + resellersByPeriod[*resellers[i].BillPeriod] = append(resellersByPeriod[*resellers[i].BillPeriod], resellers[i].ResellerID) + + r, e := d.Cache.Get(resellers[i].ResellerID, "reseller", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the reseller [ %v ]. Error: %v\n", resellers[i].ResellerID, e) + + return + + } + + reseller := r.(cusModels.Reseller) + + for j := range reseller.Customers { + + for k := range reseller.Customers[j].Products { + + cdrByReseller[resellers[i].ResellerID] = append(cdrByReseller[resellers[i].ResellerID], reseller.Customers[j].Products[k].ProductID) + + } + + } + + } + + customersByPeriod := make(map[string][]string) + cdrByCustomer := make(map[string][]string) + + for i := range customers { + + if !(*customers[i].Billable) { + + continue + + } + + customersByPeriod[*customers[i].BillPeriod] = append(customersByPeriod[*customers[i].BillPeriod], customers[i].CustomerID) + + c, e := d.Cache.Get(customers[i].CustomerID, "customer", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the customer [ %v ]. Error: %v\n", customers[i].CustomerID, e) + + return + + } + + customer := c.(cusModels.Customer) + + for j := range customer.Products { + + cdrByCustomer[customers[i].CustomerID] = append(cdrByCustomer[customers[i].CustomerID], customer.Products[j].ProductID) + + } + + } + + // 4) invocation of ProcessInvoice with each reseller generating the metadata needed + + billrunSize := int64(0) + + for _, n := range resellersByPeriod { + + billrunSize += int64(len(n)) + + } + + for _, n := range customersByPeriod { + + billrunSize += int64(len(n)) + + } + + billrunID, e := d.createBillRun(billrunSize, "System-wide autonomous generation") + + if e != nil { + + if billrunID != "" { + + l.Warning.Printf("[DB] Something unexpected is actually happening... Will keep working as if nothing.Error: %v\n", e) + + } else { + + l.Warning.Printf("[DB] Something wrong happened when creating a new billrun, check with the administrator. Error: %v\n", e) + + return + + } + + } + + wg, pipe = d.startPool(billrunSize) + + for i, p := range periods { + + for _, res := range resellersByPeriod[i] { + + wg.Add(1) + + invoice, e := d.createInvoice(p, res, "reseller") + + if e != nil { + + l.Warning.Printf("[DB] Something wrong happened when creating a new invoice for org [ %v ], check with the administrator. Error: %v\n", res, e) + + wg.Done() + preProcFailedInvoices[billrunID]++ + + continue + + } + + md := make(map[string]interface{}) + + md["type"] = "reseller" + md["organization"] = res + md["billrun"] = billrunID + md["period"] = p + md["cdr"] = strings.Join(cdrByReseller[res], ",") + md["token"] = token + md["invoice"] = invoice + + pipe <- md + + } + + for _, cus := range customersByPeriod[i] { + + wg.Add(1) + + invoice, e := d.createInvoice(p, cus, "customer") + + if e != nil { + + l.Warning.Printf("[DB] Something wrong happened when creating a new invoice for org [ %v ], check with the administrator. Error: %v\n", cus, e) + + wg.Done() + preProcFailedInvoices[billrunID]++ + + continue + + } + + md := make(map[string]interface{}) + + md["type"] = "customer" + md["organization"] = cus + md["billrun"] = billrunID + md["period"] = p + md["cdr"] = strings.Join(cdrByCustomer[cus], ",") + md["token"] = token + md["invoice"] = invoice + + pipe <- md + + } + + } + + } else { + + l.Trace.Printf("[DB] Starting the invoice generation pre-processing for specific reseller/customer.\n") + + var periods map[string]period + var customers []string + var today time.Time + var cdrs []string + var window period + var ty string + var e error + + cuscdrs := make(map[string][]string) + + periods = d.getPeriods(today) + + if org, exists := metadata["reseller"]; exists { + + r, e := d.Cache.Get(org, "reseller", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the reseller. Error: %v\n", e) + + return + + } + + o := r.(cusModels.Reseller) + window = periods[*o.BillPeriod] + ty = "reseller" + + for i := range o.Customers { + + customers = append(customers, o.Customers[i].CustomerID) + var cuscdr []string + + for j := range o.Customers[i].Products { + + cdrs = append(cdrs, o.Customers[i].Products[j].ProductID) + + cuscdr = append(cuscdr, o.Customers[i].Products[j].ProductID) + + } + + cuscdrs[o.Customers[i].CustomerID] = cuscdr + + } + + } + + if org, exists := metadata["customer"]; exists { + + c, e := d.Cache.Get(org, "customer", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the customer. Error: %v\n", e) + + return + + } + + o := c.(cusModels.Customer) + window = periods[*o.BillPeriod] + ty = "customer" + + for i := range o.Products { + + cdrs = append(cdrs, o.Products[i].ProductID) + + } + + } + + if value, exists := metadata["period"]; exists { + + window = value.(period) + + } + + invoice, e := d.createInvoice(window, metadata[ty].(string), ty) + + if e != nil || invoice == "" { + + l.Warning.Printf("[DB] Something wrong happened when creating a new invoice for org [ %v ], check with the administrator. Error: %v\n", metadata[ty], e) + + return + + } + + wg, pipe = d.startPool(int64(1 + len(customers))) + + wg.Add(1) + + md := make(map[string]interface{}) + + md["type"] = ty + md["organization"] = metadata[ty] + md["billrun"] = metadata["billrun"] + md["period"] = window + md["cdr"] = strings.Join(cdrs, ",") + md["token"] = token + md["invoice"] = invoice + + pipe <- md + + if len(customers) != 0 { + + b := models.BillRun{ + ID: metadata["billrun"].(strfmt.UUID), + InvoicesCount: int64(1 + len(customers)), + } + + if e = d.updateBillrun(b); e != nil { + + l.Warning.Printf("[DB] The invoices count of the billrun [ %v ] couldn't be updated. Error: %v.\n", metadata["billrun"], e) + + } + + for _, cus := range customers { + + invoice, e := d.createInvoice(window, cus, "customer") + + if e != nil && invoice == "" { + + l.Warning.Printf("[DB] Something wrong happened when creating a new invoice for org [ %v ], check with the administrator. Error: %v\n", cus, e) + + continue + + } + + wg.Add(1) + + md := make(map[string]interface{}) + + md["type"] = "customer" + md["organization"] = cus + md["billrun"] = metadata["billrun"] + md["period"] = window + md["cdr"] = strings.Join(cuscdrs[cus], ",") + md["token"] = token + md["invoice"] = invoice + + pipe <- md + + } + + } + + } + + l.Trace.Printf("[DB] Invoice generation pre-processing completed.\n") + + wg.Done() + + return + +} + +// startPool job is to initiate the pool of workers and provide to the invoker +// with the associated waitgroup and the feed channel to add task to the pool. +// Parameters: +// - buffer: the expected size of taks the pool will need to handle. +// Returns: +// - the WaitGroup linked to the pool of workers. +// - the map[string]interface channel used to send the information needed for +// the invoice generation process. +func (d *DbParameter) startPool(buffer int64) (*sync.WaitGroup, chan<- map[string]interface{}) { + + l.Trace.Printf("[DB][WorkersPool] Pool start invoked!.\n") + + if d.workersPool.bufferSize < buffer { + + d.workersPool.bufferSize = buffer + + } + + if !d.workersPool.poolActive { + + l.Trace.Printf("[DB][WorkersPool] Pool inactive, generating one.\n") + + d.workersPool.mutex.Lock() + + var wg sync.WaitGroup + + d.workersPool.poolActive = true + d.workersPool.sync = &wg + d.workersPool.results = make(chan workerResult, d.workersPool.bufferSize) + d.workersPool.metadata = make(chan map[string]interface{}, d.workersPool.bufferSize) + + d.workersPool.mutex.Unlock() + + for i := 0; i < d.workersPool.workers; i++ { + + l.Trace.Printf("[DB][WorkersPool] Starting pool worker #%v.\n", i) + + go d.invoiceProcessor(i, d.workersPool.metadata, d.workersPool.results) + + } + + go d.poolResults(d.workersPool.sync, d.workersPool.results) + + wg.Add(1) + + go d.endPool(d.workersPool.sync, d.workersPool.metadata, d.workersPool.results) + + } + + return d.workersPool.sync, d.workersPool.metadata + +} + +// poolResults job is to process the results of the concurrent invoice +// generation processes and update the linked billrun accordingly. +// Parameters: +// - wg: the WaitGroup linked to the pool of workers. +// - results: a workerResult channel to receive the results of the invoice +// generation process. +func (d *DbParameter) poolResults(wg *sync.WaitGroup, results <-chan workerResult) { + + l.Trace.Printf("[DB][Worker] Results processing worker started.\n") + + for r := range results { + + b := models.BillRun{ + ID: r.billrun, + AmountInvoiced: r.amount, + OrganizationsInvolved: pq.StringArray([]string{r.organization}), + Status: &r.status, + } + + if e := d.updateBillrun(b); e != nil { + + l.Warning.Printf("[DB][Worker] Billrun [ %v ][ %v ] couldn't be updated, check with the administrator. Error: %v\n", r.billrun, r.organization, e) + + } else { + + l.Trace.Printf("[DB][Worker] Billrun [ %v ] updated successfully.\n", r.billrun) + + } + + wg.Done() + + } + + l.Trace.Printf("[DB][Worker] Results channel closed, worker task completed.\n") + + return + +} + +// endPool job is to wait until all the information in the metadata channel +// has been consummed by the workers and then close the channels used by the +// pool of workers. +// Parameters: +// - wg: the WaitGroup linked to the pool of workers. +// - metadata: a map[string]interface channel used to send the information +// needed for the invoice generation process. +// - results: a workerResult channel to report the results of the invoice +// generation process. +func (d *DbParameter) endPool(wg *sync.WaitGroup, metadata chan map[string]interface{}, results chan workerResult) { + + l.Trace.Printf("[DB][WorkersPool] Clean pool mechanism invoked and waiting for workers to finish.\n") + + wg.Wait() + + d.workersPool.mutex.Lock() + + d.workersPool.poolActive = false + close(metadata) + close(results) + + d.workersPool.mutex.Unlock() + + l.Trace.Printf("[DB][WorkersPool] Workers finished, pool cleaning process completed.\n") + + return + +} + +// invoiceProcessor is the core-function of the workers in the pool, its job +// is to generate an invoice based on the information provided based on the +// information provided via the metadata channel and provide the reults of +// the generation back via the resutls channel. +// Parameters: +// - metadata: a map[string]interface channel to receive objects containing all +// the data needed to generate an invoice. +// - results: a workerResult channel to report the end result of the processing. +func (d *DbParameter) invoiceProcessor(worker int, metadata <-chan map[string]interface{}, results chan<- workerResult) { + + l.Trace.Printf("[DB][Worker #%v] Starting an invoce processing worker.\n", worker) + + // meta: org, type, cdrs, billrun, period, regenerate(bool) +MainLoop: + for m := range metadata { + + l.Trace.Printf("[DB][Worker #%v] Starting processing of organization [ %v ].\n", worker, m["organization"]) + + d.Metrics["count"].With(prometheus.Labels{"type": "Invoice processing started"}).Inc() + countTime := time.Now().UnixNano() + + var invoice models.Invoice + var items []datamodels.JSONdb + + discount := float64(0) + invoiceTotal := float64(0) + invoice.Items = make(datamodels.JSONdb) + + // 0) put everything in vars + token := m["token"].(string) + orgID := m["organization"].(string) + orgType := m["type"].(string) + orgCDRs := m["cdr"].(string) + billrunID := m["billrun"].(strfmt.UUID) + invoicePeriod := m["period"].(period) + invoiceID := m["invoice"].(strfmt.UUID) + + resultERROR := workerResult{ + amount: float64(0), + billrun: billrunID, + organization: orgID, + status: "ERROR", + } + + // 1) invoice to processing + state := "PROCESSING" + invoice.ID = invoiceID + invoice.BillRunID = billrunID + invoice.OrganizationID = orgID + invoice.Status = &state + + // 6) save/update the complete invoice + if e := d.updateInvoice(invoice); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't update the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + results <- resultERROR + + if e = d.errorInvoice(invoiceID); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + } + + continue MainLoop + + } + + // 2) get the CDRs and skus + var CDRs []*cdrModels.CReport + + for _, o := range strings.Split(orgCDRs, ",") { + + id := fmt.Sprintf("%v?%v?%v", o, invoicePeriod.from, invoicePeriod.to) + + cdr, e := d.Cache.Get(id, "cdr", token) + + if e != nil { + + l.Warning.Printf("[DB][Worker #%v] Something went wrong while retrieving the associated CDRs. Error: %v\n", worker, e) + + results <- resultERROR + + if e = d.errorInvoice(invoiceID); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + } + + continue MainLoop + + } + + CDRs = append(CDRs, cdr.([]*cdrModels.CReport)...) + + } + + s, e := d.Cache.Get("ALL", "sku", token) + + if e != nil { + + l.Warning.Printf("[DB][Worker #%v] Something went wrong while retrieving the sku list. Error: %v\n", worker, e) + + results <- resultERROR + + if e = d.errorInvoice(invoiceID); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + } + + continue MainLoop + + } + + SKUs := make(map[string]string) + + for _, k := range s.([]*pmModels.Sku) { + + SKUs[*k.Name] = k.ID + + } + + // 3) get the details of the organization and fill the invoice + if orgType == "reseller" { + + r, e := d.Cache.Get(orgID, "reseller", token) + + if e != nil { + + l.Warning.Printf("[DB][Worker #%v] Something went wrong while retrieving the reseller. Error: %v\n", worker, e) + + results <- resultERROR + + if e = d.errorInvoice(invoiceID); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + } + + continue MainLoop + + } + + o := r.(cusModels.Reseller) + + invoice.BillingContact = o.BillContact + invoice.Currency = o.BillCurrency + invoice.OrganizationName = o.Name + discount = o.Discount + + } else { + + c, e := d.Cache.Get(orgID, "customer", token) + + if e != nil { + + l.Warning.Printf("[DB][Worker #%v] Something went wrong while retrieving the customer. Error: %v\n", worker, e) + + results <- resultERROR + + if e = d.errorInvoice(invoiceID); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + } + + continue MainLoop + + } + + o := c.(cusModels.Customer) + + invoice.BillingContact = o.BillContact + invoice.Currency = o.BillCurrency + invoice.OrganizationName = o.Name + discount = o.Discount + + } + + // 4) process the CDRs + // we split the load by product/account + for _, product := range strings.Split(orgCDRs, ",") { + + if product == "" { + + continue + + } + + var costBreakup []datamodels.JSONdb + + grossCost := float64(0) + acc := make(datamodels.JSONdb) + + acc["ID"] = product + acc["discountRate"] = discount + custId, custName, e := d.getCustomerData(product, token) + + if e != nil { + + l.Warning.Printf("[DB][Worker #%v] Something went wrong while retrieving the customer data linked to product [ %v ]. Error: %v\n", worker, product, e) + + results <- resultERROR + + if e = d.errorInvoice(invoiceID); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + } + + continue MainLoop + + } + + acc["customerID"] = custId + acc["customerName"] = custName + + // let's go sku by sku + for kind := range SKUs { + + var resourceList []datamodels.JSONdb + skudata := make(datamodels.JSONdb) + cost := make(datamodels.JSONdb) + + skudata["skuName"] = kind + skudata["skuCost"] = float64(0) + skudata["skuAggregatedDiscount"] = float64(0) + skudata["skuNet"] = float64(0) + + // go through the cdrs looking for the product id + for i := range CDRs { + + if CDRs[i].AccountID != product { + + continue + + } + + usage := CDRs[i].Usage + + UsageLoop: + // once found let's go across the usage + for j := range usage { + + // if not the type, skip + if usage[j].ResourceType != kind { + + // if it's server, let's check in detail + if usage[j].ResourceType != "server" { + + continue + + } + + } + + data := usage[j] + resource := make(datamodels.JSONdb) + + // In case the resource doesn't have id/name let's use the sku to identify it somehow + if data.ResourceID != "" { + + resource["resourceID"] = data.ResourceID + + } else { + + resource["resourceID"] = kind + + } + + if data.ResourceName != "" { + + resource["resourceName"] = data.ResourceName + + } else { + + resource["resourceName"] = kind + + } + + resource["metadata"] = data.Metadata + resource["usage"] = data.UsageBreakup + resource["skuUnits"] = d.getFloat(float64(1) / float64(3)) + + skuCostBreakup := make(datamodels.JSONdb) + + // Update of costs + if data.Cost["costBreakup"] != nil { + + for _, value := range data.Cost["costBreakup"].([]interface{}) { + + k := value.(map[string]interface{}) + + if k["sku"] != kind { + + continue + + } + + skudata["skuNet"] = d.getFloat(skudata["skuNet"]) + d.getFloat(k["sku-net"]) + skudata["skuCost"] = d.getFloat(skudata["skuCost"]) + d.getFloat(k["sku-cost"]) + skuCostBreakup[k["sku-state"].(string)] = d.getFloat(skuCostBreakup[k["sku-state"].(string)]) + d.getFloat(k["sku-net"]) + + } + + } + + resource["costBreakup"] = skuCostBreakup + + // if sku not found, skip + if len(skuCostBreakup) == 0 { + + continue + + } + + // resourceList update... + for i, duplicated := range resourceList { + + // if the resource is already in the list, create a newone = oldOne + newData + if duplicated["resourceID"].(string) == resource["resourceID"].(string) && + duplicated["resourceName"].(string) == resource["resourceName"].(string) && + fmt.Sprintf("%v", duplicated["metadata"]) == fmt.Sprintf("%v", resource["metadata"]) { + + newResource := make(datamodels.JSONdb) + + if data.ResourceID != "" { + + newResource["resourceID"] = data.ResourceID + + } else { + + newResource["resourceID"] = kind + + } + + if data.ResourceName != "" { + + newResource["resourceName"] = data.ResourceName + + } else { + + newResource["resourceName"] = kind + + } + + newResource["metadata"] = data.Metadata + newResource["skuUnits"] = d.getFloat(float64(1)/float64(3)) + d.getFloat(duplicated["skuUnits"]) + + newUse := make(datamodels.JSONdb) + newCost := make(datamodels.JSONdb) + + oldCost := duplicated["costBreakup"].(datamodels.JSONdb) + oldUse := duplicated["usage"].(datamodels.JSONdb) + + for x, v := range data.UsageBreakup { + + if oUse, exists := oldUse[x]; exists { + + newUse[x] = d.getFloat(oUse) + d.getFloat(v) + + } else { + + newUse[x] = d.getFloat(v) + + } + + } + + for x, v := range skuCostBreakup { + + if oCost, exists := oldCost[x]; exists { + + newCost[x] = d.getFloat(oCost) + d.getFloat(v) + + } else { + + newUse[x] = d.getFloat(v) + + } + + } + + newResource["usage"] = newUse + newResource["costBreakup"] = newCost + + resourceList[i] = newResource + + continue UsageLoop + + } + + } + + resourceList = append(resourceList, resource) + + } + + } + + if d.getFloat(skudata["skuNet"]) == float64(0) { + + continue + + } + + skudata["skuAggregatedDiscount"] = d.getNiceFloat(d.getFloat(skudata["skuCost"]) - d.getFloat(skudata["skuNet"])) + + cost["sku"] = skudata + cost["resourceList"] = resourceList + + grossCost = grossCost + d.getFloat(skudata["skuNet"]) + costBreakup = append(costBreakup, cost) + + } + + acc["grossCost"] = d.getNiceFloat(grossCost) + acc["discount"] = d.getNiceFloat(grossCost * discount) + acc["netCost"] = d.getNiceFloat(grossCost - (grossCost * discount)) + acc["costBreakup"] = costBreakup + + items = append(items, acc) + + invoiceTotal = invoiceTotal + d.getNiceFloat(grossCost-(grossCost*discount)) + + } + + // 5) complete the invoice + invoice.AmountInvoiced = invoiceTotal + invoice.Items["accounts"] = items + + state = "FINISHED" + invoice.Status = &state + + // 6) save/update the complete invoice + if e := d.updateInvoice(invoice); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't save the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + results <- resultERROR + + if e = d.errorInvoice(invoiceID); e != nil { + + l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + } + + continue MainLoop + + } + + // 7) update the billrun + // The invoices with 0 are ok now + // if invoiceTotal == float64(0) { + + // l.Warning.Printf("[DB][Worker #%v] Invoice [ %v ] has invoiced 0, discarding...", worker, invoiceID) + + // results <- resultERROR + + // if e = d.errorInvoice(invoiceID); e != nil { + + // l.Warning.Printf("[DB][Worker #%v] Couldn't set as ERROR the invoice [ %v ] for organization [ %v ], check with the administrator. Error: %v\n", worker, invoiceID, orgID, e) + + // } + + // } else { + + results <- workerResult{ + amount: invoiceTotal, + billrun: billrunID, + organization: orgID, + status: "FINISHED", + } + + // } + + l.Trace.Printf("[DB][Worker #%v] Finished processing of organization [ %v ].\n", worker, m["organization"]) + + d.Metrics["count"].With(prometheus.Labels{"type": "Invoices processing completed"}).Inc() + + invTotal++ + invTime += float64(time.Now().UnixNano() - countTime) + + d.Metrics["time"].With(prometheus.Labels{"type": "Invoice generation average time"}).Set(invTime / invTotal / float64(time.Millisecond)) + + } + + l.Trace.Printf("[DB][Worker #%v] No more data to be processed, stopping worker.\n", worker) + + return + +} + +// getCustomerData job is to retrieve the id and name associated to the customer +// whose product id is provided. +// Parameters: +// - p: string with the product id. +// - token: a string with an optional keycloak bearer token. +// Returns: +// - id: string with the linked customer id. +// - name: string with the linked customer name. +func (d *DbParameter) getCustomerData(p, token string) (id, name string, err error) { + + x, e := d.Cache.Get(p, "product", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the product info for id [ %v ]. Error: %v\n", p, e) + + err = e + + return + + } + + product := x.(cusModels.Product) + + c, e := d.Cache.Get(product.CustomerID, "customer", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the customer info for id [ %v ]. Error: %v\n", product.CustomerID, e) + + err = e + + return + + } + + customer := c.(cusModels.Customer) + + id = customer.CustomerID + name = customer.Name + + return + +} + +// updateBillrun job is to update the information of the billrun saved in +// the system with the information provided in the incoming billrun object. +// Parameters: +// - o: billrun object with the date to update in the system. +// Returns: +// - e in case of any error happening. +func (d *DbParameter) updateBillrun(o models.BillRun) (e error) { + + l.Trace.Printf("[DB] Attempting to update the billrun [ %v ].\n", o.ID) + + var origin models.BillRun + + r := d.Db.Where(&models.BillRun{ID: o.ID}).First(&origin).Error + + if errors.Is(r, gorm.ErrRecordNotFound) { + + l.Warning.Printf("[DB] Something went wrong, billrun [ %v ] not found in the system.\n", o.ID) + + e = errors.New("billrun not found") + + return + + } + + if r != nil { + + l.Warning.Printf("[DB] Something went wrong. Error: %v\n", r) + + e = r + + } else { + + // The update itself + if o.Status != nil && *o.Status == "ERROR" { + + if len(o.OrganizationsInvolved) > 0 && !d.contains(origin.InvoicesErrorList, o.OrganizationsInvolved[0]) { + + o.InvoicesErrorList = append(origin.InvoicesErrorList, o.OrganizationsInvolved[0]) + + } else { + + o.InvoicesErrorList = origin.InvoicesErrorList + + } + + o.InvoicesErrorCount = int64(len(o.InvoicesErrorList)) + + } else { + + status := "PROCESSING" + o.Status = &status + + } + + if len(o.OrganizationsInvolved) > 0 && !d.contains(origin.OrganizationsInvolved, o.OrganizationsInvolved[0]) { + + o.OrganizationsInvolved = append(origin.OrganizationsInvolved, o.OrganizationsInvolved[0]) + + } else { + + o.OrganizationsInvolved = origin.OrganizationsInvolved + + } + + o.InvoicesProcessedCount = int64(len(o.OrganizationsInvolved)) + o.AmountInvoiced += origin.AmountInvoiced + + if (origin.InvoicesCount-preProcFailedInvoices[o.ID] <= o.InvoicesProcessedCount) && (o.Status != nil && (*o.Status != "ERROR" || o.InvoicesErrorCount <= 0)) { + + d.Metrics["count"].With(prometheus.Labels{"type": "Billruns completed"}).Inc() + + status := "FINISHED" + o.Status = &status + + } + + if e = d.Db.Model(origin).Updates(o).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while updating the billrun [ %v ]. Error: %v\n", o.ID, e) + + } else { + + l.Trace.Printf("[DB] Billrun [ %v ] updated successfully.\n", o.ID) + + } + + } + + return +} + +// updateInvoice job is to update the information of the invoice saved in +// the system with the information provided in the incoming invoice object. +// Parameters: +// - o: invoice object with the date to update in the system. +// Returns: +// - e in case of any error happening. +func (d *DbParameter) updateInvoice(o models.Invoice) (e error) { + + l.Trace.Printf("[DB] Attempting to update the invoice [ %v ].\n", o.ID) + + var origin models.Invoice + + r := d.Db.Where(&models.Invoice{ID: o.ID}).First(&origin).Error + + if errors.Is(r, gorm.ErrRecordNotFound) { + + l.Warning.Printf("[DB] Something went wrong, invoice [ %v ] not found in the system.\n", o.ID) + + e = errors.New("invoice not found") + + return + + } + + if r != nil { + + l.Warning.Printf("[DB] Something went wrong. Error: %v\n", r) + + e = errors.New("invoice not found") + + } else { + + if e = d.Db.Model(origin).Updates(o).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while updating the invoice [ %v ]. Error: %v\n", o.ID, e) + + } else { + + l.Trace.Printf("[DB] Invoice [ %v ] updated successfully.\n", o.ID) + + } + + } + + return +} + +// errorInvoice job is to mark the invoice linked to the provided ID +// with ERROR status. +// Parameters: +// - id: a UUID string with the associated ID to the invoice to ERROR. +// Returns: +// - e in case of any error happening. +func (d *DbParameter) errorInvoice(id strfmt.UUID) (e error) { + + l.Trace.Printf("[DB] Attempting to delete de failed invoice [ %v ].\n", id) + + var origin models.Invoice + + r := d.Db.Where(&models.Invoice{ID: id}).First(&origin).Error + + if errors.Is(r, gorm.ErrRecordNotFound) { + + l.Warning.Printf("[DB] Something went wrong, invoice [ %v ] not found in the system.\n", id) + + e = errors.New("invoice not found") + + return + + } + + if r != nil { + + l.Warning.Printf("[DB] Something went wrong. Error: %v\n", r) + + e = errors.New("invoice not found") + + } else { + + status := "ERROR" + + if e = d.Db.Model(origin).Updates(&models.Invoice{Status: &status}).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while ERRORing the invoice [ %v ]. Error: %v\n", id, e) + + } else { + + l.Trace.Printf("[DB] Invoice [ %v ] ERRORed successfully.\n", id) + + } + + } + + return +} + +// getCDRS job is to retrieve the list of products linked to an organization ID +// double checking if it's a reseller or a customer, providing this information +// also with the retrieved list. +// Parameters: +// - orgID: a string with the organization ID whose product list is going +// to be retrieved. +// - token: a string with an optional keycloak bearer token. +// Returns: +// - ty: string containing the type of organization +// - cdrs: string containing a coma-separated list with the IDs of the linked +// products to the specified organization. +// - e in case of any error happening. +func (d *DbParameter) getCDRS(orgID, token string) (ty, cdrs string, err error) { + + l.Trace.Printf("[DB] Attempting to get the CDRs for the organization [ %v ].\n", orgID) + + var customers []*cusModels.Customer + + ty = "reseller" + + r, e := d.Cache.Get(orgID, ty, token) + + if e != nil { + + l.Trace.Printf("[DB] Something went wrong while retrieving de organization [ %v ] as a reseller, trying with it as a customer... Error: %v\n", orgID, e) + + ty = "customer" + + c, e := d.Cache.Get(orgID, ty, token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving de organization [ %v ] as a customer. Error: %v\n", orgID, e) + + err = e + + return + + } + + customer := c.(cusModels.Customer) + + customers = append(customers, &customer) + + } else { + + reseller := r.(cusModels.Reseller) + + customers = append(customers, reseller.Customers...) + + } + + for i := range customers { + + customer := *customers[i] + + for j := range customer.Products { + + if cdrs != "" { + + cdrs = string(customer.Products[j].ProductID) + + } else { + + cdrs = cdrs + "," + string(customer.Products[j].ProductID) + + } + + } + + } + + return + +} + +// ReRunBillRun processes the billruns in the system and re-run them in order +// to try to fix the ones that failed. +// Parameters: +// - id: a UUID string with the associated ID to the billrun that should be check. +// - months: int64 indicating the amount of months to go back in time to check +// for failed billruns. +// - token: a string with an optional keycloak bearer token. +// Returns: +// - status: a int indicating the result of the reRun execution +// - e in case of any error happening. +func (d *DbParameter) ReRunBillRun(id strfmt.UUID, months *int64, token string) (status int, e error) { + + l.Trace.Printf("[DB] Attempting to re-run failed invoices on billrun [ %v ].\n", id) + + var pipe chan<- map[string]interface{} + var invoices []*models.Invoice + var wg *sync.WaitGroup + var timeWindow string + var f, t time.Time + + state := "FINISHED" + + if id == "" { + + m := int64(3) + + if months != nil { + + m = *months + + } + + timeWindow = d.getWindow("GenerationTimestamp", m) + + } + + r := d.Db.Where(timeWindow).Not(&models.Invoice{Status: &state}).Where(&models.Invoice{BillRunID: id}).Find(&invoices).Error + + if errors.Is(r, gorm.ErrRecordNotFound) { + + status = StatusMissing + + e = errors.New("there's nothing to re-run") + + return + + } + + if r != nil { + + status = StatusFail + + e = r + + } else { + + status = StatusOK + + for _, invoice := range invoices { + + wg, pipe = d.startPool(int64(100)) + + wg.Add(1) + + f = (time.Time)(invoice.PeriodStartDate) + from := time.Date(f.Year(), f.Month(), f.Day(), 0, 0, 0, 0, time.UTC) + + t = (time.Time)(invoice.PeriodEndDate) + to := time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, time.UTC) + + ty, cdrs, e := d.getCDRS(invoice.OrganizationID, token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving de cdrs associated to the organization [ %v ]. Error: %v\n", invoice.OrganizationID, e) + + continue + + } + + md := make(map[string]interface{}) + + md["type"] = ty + md["organization"] = invoice.OrganizationID + md["billrun"] = invoice.BillRunID + md["cdr"] = cdrs + md["regenerate"] = true + md["token"] = token + md["invoice"] = invoice.ID + md["period"] = period{ + from: (strfmt.DateTime)(from), + to: (strfmt.DateTime)(to), + } + + pipe <- md + + } + + wg.Done() + + } + + return + +} diff --git a/services/billing/server/invoiceManager/invoiceManager.go b/services/billing/server/invoiceManager/invoiceManager.go new file mode 100644 index 0000000..7afc12d --- /dev/null +++ b/services/billing/server/invoiceManager/invoiceManager.go @@ -0,0 +1,432 @@ +package invoiceManager + +import ( + "context" + "net/http" + "strings" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/invoice_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// InvoiceManager is the struct defined to group and contain all the methods +// that interact with the invoice subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +// - BasePath: a string with the base path of the system. +type InvoiceManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager + BasePath string +} + +// New is the function to create the struct InvoiceManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// - bp: a string containing the base path of the service. +// Returns: +// - InvoiceManager: struct to interact with InvoiceManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *InvoiceManager { + + l.Trace.Printf("[InvoiceManager] Generating new invoiceManager.\n") + + monit.InitEndpoint("invoice") + + return &InvoiceManager{ + db: db, + monit: monit, + BasePath: bp, + } + +} + +func (m *InvoiceManager) getToken(param *http.Request) (token string) { + + if len(param.Header.Get("Authorization")) > 0 { + + token = strings.Fields(param.Header.Get("Authorization"))[1] + + } + + return + +} + +// GenerateInvoiceForCustomer (Swagger func) is the function behind +// the (POST) endpoint /invoice/customer/{id} +// It's job is to start the generation of the invoices associated with the +// requested customer in the system within the optional declared time-window. +func (m *InvoiceManager) GenerateInvoiceForCustomer(ctx context.Context, params invoice_management.GenerateInvoiceForCustomerParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] GenerateInvoiceForCustomer endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + var from, to strfmt.DateTime + + token := m.getToken(params.HTTPRequest) + + if params.From != nil { + + from = *params.From + + } + + if params.To != nil { + + to = *params.To + + } + + billrun, e := m.db.GenerateInvoicesBy("customer", params.ID, token, from, to) + + if e != nil { + + s := "Problem while trying to generate the Invoice: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/invoice/customer/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGenerateInvoiceForCustomerInternalServerError().WithPayload(&errorReturn) + + } + + acceptedReturn := models.ItemCreatedResponse{ + APILink: m.BasePath + "/billrun/" + billrun, + Message: "The request has been added to the queue", + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "POST", "route": "/invoice/customer/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGenerateInvoiceForCustomerAccepted().WithPayload(&acceptedReturn) + +} + +// GenerateInvoiceForReseller (Swagger func) is the function behind +// the (POST) endpoint /invoice/reseller/{id} +// It's job is to start the generation of the invoices associated with the +// requested reseller in the system within the optional declared time-window. +func (m *InvoiceManager) GenerateInvoiceForReseller(ctx context.Context, params invoice_management.GenerateInvoiceForResellerParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] GenerateInvoiceForReseller endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + var from, to strfmt.DateTime + + token := m.getToken(params.HTTPRequest) + + if params.From != nil { + + from = *params.From + + } + + if params.To != nil { + + to = *params.To + + } + + billrun, e := m.db.GenerateInvoicesBy("reseller", params.ID, token, from, to) + + if e != nil { + + s := "Problem while trying to generate the Invoice: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/invoice/reseller/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGenerateInvoiceForResellerInternalServerError().WithPayload(&errorReturn) + + } + + acceptedReturn := models.ItemCreatedResponse{ + APILink: m.BasePath + "/billrun/" + billrun, + Message: "The request has been added to the queue", + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "POST", "route": "/invoice/reseller/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGenerateInvoiceForResellerAccepted().WithPayload(&acceptedReturn) + +} + +// GetInvoice (Swagger func) is the function behind the (GET) endpoint +// /invoice/{id} +// It's job is to provide the requested invoice from the system +func (m *InvoiceManager) GetInvoice(ctx context.Context, params invoice_management.GetInvoiceParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] GetInvoice endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + object, e := m.db.GetInvoice(params.ID) + + if e != nil { + + s := "Problem while retrieving the Invoice from the db: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/invoice/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoiceInternalServerError().WithPayload(&errorReturn) + + } + + if object != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/invoice/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoiceOK().WithPayload(object) + } + + s := "The Invoice doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/invoice/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoiceNotFound().WithPayload(&missingReturn) + +} + +// GetInvoicesByCustomer (Swagger func) is the function behind +// the (GET) endpoint /invoice/customer/{id} +// It's job is to provide the invoices associated to the requested customer +// in the system. +func (m *InvoiceManager) GetInvoicesByCustomer(ctx context.Context, params invoice_management.GetInvoicesByCustomerParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] GetInvoicesByCustomer endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + object, e := m.db.GetInvoicesByOrganization(params.ID, params.Months) + + if e != nil { + + s := "Problem while retrieving the Invoice from the db: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/invoice/customer/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoicesByCustomerInternalServerError().WithPayload(&errorReturn) + + } + + if object != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/invoice/customer/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoicesByCustomerOK().WithPayload(object) + } + + s := "The invoice doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/invoice/customer/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoicesByCustomerNotFound().WithPayload(&missingReturn) + +} + +// GetInvoicesByReseller (Swagger func) is the function behind +// the (GET) endpoint /invoice/reseller/{id} +// It's job is to provide the invoices associated to the requested reseller +// in the system. +func (m *InvoiceManager) GetInvoicesByReseller(ctx context.Context, params invoice_management.GetInvoicesByResellerParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] GetInvoicesByReseller endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + object, e := m.db.GetInvoicesByOrganization(params.ID, params.Months) + + if e != nil { + + s := "Problem while retrieving the Invoice from the db: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/invoice/reseller/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoicesByResellerInternalServerError().WithPayload(&errorReturn) + + } + + if object != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/invoice/reseller/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoicesByResellerOK().WithPayload(object) + } + + s := "The Invoice doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/invoice/reseller/" + string(params.ID)}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewGetInvoicesByResellerNotFound().WithPayload(&missingReturn) + +} + +// ListInvoices (Swagger func) is the function behind the (GET) endpoint +// /invoice +// It's job is to provide all the invoices contained in the system. +func (m *InvoiceManager) ListInvoices(ctx context.Context, params invoice_management.ListInvoicesParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] ListInvoices endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + object, e := m.db.ListInvoices(params.Model) + + if e != nil { + + s := "Problem while retrieving the Invoices from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/invoice"}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewListInvoicesInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/invoice"}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewListInvoicesOK().WithPayload(object) + +} + +// ListCustomerInvoices (Swagger func) is the function behind the (GET) endpoint +// /invoice/customer +// It's job is to provide all the customers invoices contained in the system. +func (m *InvoiceManager) ListCustomerInvoices(ctx context.Context, params invoice_management.ListCustomerInvoicesParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] ListCustomerInvoices endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + object, e := m.db.ListInvoices(&models.Invoice{OrganizationType: "customer"}) + + if e != nil { + + s := "Problem while retrieving the Customers Invoices from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/invoice/customer"}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewListCustomerInvoicesInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/invoice/customer"}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewListCustomerInvoicesOK().WithPayload(object) + +} + +// ListResellerInvoices (Swagger func) is the function behind the (GET) endpoint +// /invoice/reseller +// It's job is to provide all the resellers invoices contained in the system. +func (m *InvoiceManager) ListResellerInvoices(ctx context.Context, params invoice_management.ListResellerInvoicesParams) middleware.Responder { + + l.Trace.Printf("[InvoiceManager] ListResellerInvoices endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("invoice", callTime) + + object, e := m.db.ListInvoices(&models.Invoice{OrganizationType: "reseller"}) + + if e != nil { + + s := "Problem while retrieving the Resellers Invoices from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/invoice/reseller"}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewListResellerInvoicesInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/invoice/reseller"}).Inc() + + m.monit.APIHitDone("invoice", callTime) + + return invoice_management.NewListResellerInvoicesOK().WithPayload(object) + +} diff --git a/services/billing/server/main.go b/services/billing/server/main.go new file mode 100644 index 0000000..39f22dd --- /dev/null +++ b/services/billing/server/main.go @@ -0,0 +1,176 @@ +package main + +import ( + "crypto/tls" + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/services/billing/server/metrics.go b/services/billing/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/services/billing/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/services/billing/server/security.go b/services/billing/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/services/billing/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/services/billing/server/service.go b/services/billing/server/service.go new file mode 100644 index 0000000..bcd467f --- /dev/null +++ b/services/billing/server/service.go @@ -0,0 +1,82 @@ +package main + +import ( + "net/http" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/bulkManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/invoiceManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/statusManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/triggerManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,...,N have to be customized + db := dbStart(&models.Invoice{}, &models.BillRun{}) + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + // cache linked to the dbParameter + db.Cache = cacheStart(db.Metrics["cache"]) + + bp := getBasePath() + + // Parts of the service HERE + b := bulkManager.New(db, mon) + i := invoiceManager.New(db, mon, bp) + t := triggerManager.New(db, mon, bp) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + TriggerManagementAPI: t, + BulkManagementAPI: b, + InvoiceManagementAPI: i, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} diff --git a/services/billing/server/statusManager/statusManager.go b/services/billing/server/statusManager/statusManager.go new file mode 100644 index 0000000..d028552 --- /dev/null +++ b/services/billing/server/statusManager/statusManager.go @@ -0,0 +1,325 @@ +package statusManager + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 + mutex *sync.Mutex +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + mutex = &sync.Mutex{} + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + avgTime[key] = t.UnixNano() + mutex.Unlock() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + previous, exists := avgTime[key] + mutex.Unlock() + + if exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + mutex.Lock() + delete(avgTime, key) + mutex.Unlock() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/services/billing/server/triggerManager/triggerManager.go b/services/billing/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..ce66f9e --- /dev/null +++ b/services/billing/server/triggerManager/triggerManager.go @@ -0,0 +1,104 @@ +package triggerManager + +import ( + "context" + "net/http" + "strings" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/billing/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// TriggerManager is the struct defined to group and contain all the methods +// that interact with the trigger subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +// - BasePath: a string with the base path of the system. +type TriggerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager + BasePath string +} + +// New is the function to create the struct TriggerManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// - bp: a string containing the base path of the service. +// Returns: +// - TriggerManager: struct to interact with TriggerManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *TriggerManager { + + l.Trace.Printf("[TriggerManager] Generating new triggerManager.\n") + + monit.InitEndpoint("trigger") + + return &TriggerManager{ + db: db, + monit: monit, + BasePath: bp, + } + +} + +// getToken job is to extract the Keycloak Bearer token from the http header. +// Parameters: +// - param: a pointer to the http.Request object from which extract. +// Returns: +// - token: a string containing the extracted token or an empty one in case of +// no token available. +func (m *TriggerManager) getToken(param *http.Request) (token string) { + + if len(param.Header.Get("Authorization")) > 0 { + + token = strings.Fields(param.Header.Get("Authorization"))[1] + + } + + return + +} + +// PeriodicRun (Swagger func) is the function behind the (GET) +// /trigger/periodicrun endpoint. +// It is a dummy function for reference. +func (m *TriggerManager) PeriodicRun(ctx context.Context, params trigger_management.PeriodicRunParams) middleware.Responder { + + l.Trace.Printf("[Trigger] Periodic endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + token := m.getToken(params.HTTPRequest) + + if params.Today != nil { + + go m.db.InvoicesGeneration(map[string]interface{}{"today": *params.Today}, token) + + } else { + + go m.db.InvoicesGeneration(nil, token) + + } + + acceptedReturn := models.ItemCreatedResponse{ + APILink: m.BasePath + "/billrun", + Message: "The autonomous periodic run for billing generation has been started...", + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "GET", "route": "/trigger/periodicrun"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewPeriodicRunAccepted().WithPayload(&acceptedReturn) + +} diff --git a/services/billing/swagger.yaml b/services/billing/swagger.yaml new file mode 100644 index 0000000..764c26e --- /dev/null +++ b/services/billing/swagger.yaml @@ -0,0 +1,827 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v1.0" +info: + description: An API which supports creation, deletion, listing etc of Billing + version: "1.0.0" + title: Billing Management API + contact: + email: diego@cyclops-labs.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + - name: bulkManagement + description: Actions relating to the bulk generations/retrieval of invoices. + - name: invoiceManagement + description: Actions relating to the generation and retrieval of invoices. + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - kafka-receiver + - kafka-sender + - status + - trigger + - bulk + - invoice + required: true + description: Id of the endpoint to be checked + + /trigger/periodicrun: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Periodic run of the bulk generation of invoices + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: periodicRun + responses: + '202': + description: The request for processing the periodic run had been added to the queue + schema: + $ref: "#/definitions/ItemCreatedResponse" + parameters: + - name: today + in: query + description: Datetime to override the time.now() to simulate other days + type: string + format: datetime + + /billrun: + get: + tags: + - bulkManagement + produces: + - application/json + summary: Show the status report of the billruns present in the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: ListBillRuns + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/BillRunList" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: months + in: query + description: Amount of months to have in the report + type: integer + put: + tags: + - bulkManagement + consumes: + - application/json + produces: + - application/json + summary: Try to re-run the failed invoices in all the billruns. + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: ReRunAllBillRuns + responses: + '202': + description: The request for processing had been added to the queue + schema: + $ref: "#/definitions/ItemCreatedResponse" + '404': + description: The invoice id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: months + in: query + description: Amount of months to check for failed invoices. + type: integer + /billrun/{id}: + get: + tags: + - bulkManagement + produces: + - application/json + summary: Get the status report of the billrun requested + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: GetBillRun + responses: + '200': + description: Description of a successfully operation + schema: + $ref: "#/definitions/BillRunReport" + '404': + description: The invoice id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the invoice to be checked + required: true + type: string + format: uuid + put: + tags: + - bulkManagement + consumes: + - application/json + produces: + - application/json + summary: Try to re-run the failed invoices in the billrun. + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: ReRunBillRun + responses: + '202': + description: The request for processing had been added to the queue + schema: + $ref: "#/definitions/ItemCreatedResponse" + '404': + description: The invoice id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the billrun to be re-run. + required: true + type: string + format: uuid + /billrun/organization/{id}: + get: + tags: + - bulkManagement + produces: + - application/json + summary: Show the status report of the billruns present in the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: ListBillRunsByOrganization + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/BillRunList" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the billrun to be re-run. + required: true + type: string + - name: months + in: query + description: Amount of months to have in the report + type: integer + + /invoice: + get: + tags: + - invoiceManagement + produces: + - application/json + summary: Summary for this endpoint + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: ListInvoices + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Invoice" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: model + in: body + description: Invoice model partially filled to use for the filtering of the invoices + schema: + $ref: "#/definitions/Invoice" + /invoice/{id}: + get: + tags: + - invoiceManagement + produces: + - application/json + summary: Summary for this endpoint + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: GetInvoice + responses: + '200': + description: Description of a successfully operation + schema: + $ref: "#/definitions/Invoice" + '404': + description: The invoice id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the invoice to be checked + required: true + type: string + format: uuid + + /invoice/reseller: + get: + tags: + - invoiceManagement + produces: + - application/json + summary: Retrieve resellers' invoices + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: ListResellerInvoices + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Invoice" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + /invoice/reseller/{id}: + get: + tags: + - invoiceManagement + produces: + - application/json + summary: Retrieve invoices by reseller id + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: GetInvoicesByReseller + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Invoice" + '404': + description: The invoice id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the account to be checked + required: true + type: string + - name: months + in: query + description: Amount of months to have in the report + type: integer + post: + tags: + - invoiceManagement + consumes: + - application/json + produces: + - application/json + summary: Generate invoice for the provided reseller for the provided time window or last period + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: GenerateInvoiceForReseller + responses: + '202': + description: The request for processing had been added to the queue + schema: + $ref: "#/definitions/ItemCreatedResponse" + '400': + description: Invalid input, object invalid + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the account to be checked + required: true + type: string + - name: from + in: query + description: Datetime from which to generate the invoice + type: string + format: datetime + - name: to + in: query + description: Datetime until which to generate the invoice + type: string + format: datetime + + /invoice/customer: + get: + tags: + - invoiceManagement + produces: + - application/json + summary: Retrieve customers' invoices + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: ListCustomerInvoices + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Invoice" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + /invoice/customer/{id}: + get: + tags: + - invoiceManagement + produces: + - application/json + summary: Retrieve invoices by customer id + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: GetInvoicesByCustomer + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Invoice" + '404': + description: The invoice id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the account to be checked + required: true + type: string + - name: months + in: query + description: Amount of months to have in the report + type: integer + post: + tags: + - invoiceManagement + consumes: + - application/json + produces: + - application/json + summary: Generate invoice for the provided customer for the provided time window or last period + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: GenerateInvoiceForCustomer + responses: + '202': + description: The request for processing had been added to the queue + schema: + $ref: "#/definitions/ItemCreatedResponse" + '400': + description: Invalid input, object invalid + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the account to be checked + required: true + type: string + - name: from + in: query + description: Datetime from which to generate the invoice + type: string + format: datetime + - name: to + in: query + description: Datetime until which to generate the invoice + type: string + format: datetime + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + ItemCreatedResponse: + properties: + ApiLink: + type: string + Message: + type: string + Metadata: + type: object + x-go-type: + import: + package: "gitlab.com/cyclops-enterprise/datamodels" + type: JSONdb + StringArray: + x-go-type: + import: + package: "github.com/lib/pq" + type: StringArray + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + + BillRun: + type: object + properties: + ID: + type: string + format: uuid + x-go-custom-tag: gorm:"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + AmountInvoiced: + type: number + format: double + default: 0.0 + x-go-custom-tag: gorm:"type:numeric(23,13)" + CreationTimestamp: + type: string + format: date-time + x-go-custom-tag: gorm:"type:timestamptz" + InvoicesCount: + type: integer + InvoicesErrorCount: + type: integer + InvoicesErrorList: + $ref: '#/definitions/StringArray' + x-go-custom-tag: gorm:"type:text[]" + InvoicesList: + type: array + items: + $ref: '#/definitions/InvoiceMetadata' + x-go-custom-tag: gorm:"-" + InvoicesProcessedCount: + type: integer + OrganizationsInvolved: + $ref: '#/definitions/StringArray' + x-go-custom-tag: gorm:"type:text[]" + Status: + type: string + default: QUEUED + enum: + - ERROR + - FINISHED + - PROCESSING + - QUEUED + x-go-custom-tag: gorm:"default:QUEUED" + ExecutionType: + type: string + + BillRunList: + type: object + properties: + ID: + type: string + format: uuid + AmountInvoiced: + type: number + format: double + default: 0.0 + CreationTimestamp: + type: string + format: date-time + InvoicesCount: + type: integer + InvoicesErrorCount: + type: integer + InvoicesErrorList: + $ref: '#/definitions/StringArray' + x-go-custom-tag: gorm:"type:text[]" + InvoicesProcessedCount: + type: integer + OrganizationsInvolved: + $ref: '#/definitions/StringArray' + x-go-custom-tag: gorm:"type:text[]" + Status: + type: string + default: QUEUED + enum: + - ERROR + - FINISHED + - PROCESSING + - QUEUED + + BillRunReport: + type: object + properties: + ID: + type: string + format: uuid + AmountInvoiced: + type: number + format: double + default: 0.0 + CreationTimestamp: + type: string + format: date-time + InvoicesCount: + type: integer + InvoicesErrorCount: + type: integer + InvoicesErrorList: + $ref: '#/definitions/StringArray' + x-go-custom-tag: gorm:"type:text[]" + InvoicesList: + type: array + items: + $ref: '#/definitions/InvoiceMetadata' + x-go-custom-tag: gorm:"-" + InvoicesProcessedCount: + type: integer + Status: + type: string + default: QUEUED + enum: + - ERROR + - FINISHED + - PROCESSING + - QUEUED + + Invoice: + type: object + properties: + ID: + type: string + format: uuid + x-go-custom-tag: gorm:"type:uuid;primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + AmountInvoiced: + type: number + format: double + default: 0.0 + x-go-custom-tag: gorm:"type:numeric(23,13)" + BillingContact: + type: string + BillRunID: + type: string + format: uuid + Currency: + type: string + default: CHF + enum: + - CHF + - EUR + - USD + GenerationTimestamp: + type: string + format: date-time + x-go-custom-tag: gorm:"type:timestamptz" + Items: + $ref: '#/definitions/Metadata' + x-go-custom-tag: gorm:"type:jsonb" + OrganizationID: + type: string + OrganizationName: + type: string + OrganizationType: + type: string + PaymentDeadline: + type: string + format: date + x-go-custom-tag: gorm:"type:date" + PaymentStatus: + type: string + default: UNPAID + enum: + - CANCELLED + - PAID + - UNPAID + PeriodEndDate: + type: string + format: date + x-go-custom-tag: gorm:"type:date" + PeriodStartDate: + type: string + format: date + x-go-custom-tag: gorm:"type:date" + Status: + type: string + default: NOT_PROCESSED + enum: + - ERROR + - FINISHED + - NOT_PROCESSED + - PROCESSING + x-go-custom-tag: gorm:"default:NOT_PROCESSED" + + InvoiceMetadata: + type: object + properties: + ID: + type: string + format: uuid + AmountInvoiced: + type: number + format: double + default: 0.0 + Currency: + type: string + default: CHF + enum: + - CHF + - EUR + - USD + OrganizationID: + type: string + OrganizationName: + type: string + PaymentDeadline: + type: string + format: date + PaymentStatus: + type: string + default: UNPAID + enum: + - CANCELLED + - PAID + - UNPAID + PeriodEndDate: + type: string + format: date + PeriodStartDate: + type: string + format: date + Status: + type: string + default: NOT_PROCESSED + enum: + - ERROR + - FINISHED + - NOT_PROCESSED + - PROCESSING + diff --git a/services/cdr/README.md b/services/cdr/README.md new file mode 100644 index 0000000..ec4b99a --- /dev/null +++ b/services/cdr/README.md @@ -0,0 +1,26 @@ +# CHARGE DATA REPORT SERVICE + +Cyclops Engine's Charge Data Report Service implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + diff --git a/services/cdr/client/c_d_r_management_api_client.go b/services/cdr/client/c_d_r_management_api_client.go new file mode 100644 index 0000000..f74e16b --- /dev/null +++ b/services/cdr/client/c_d_r_management_api_client.go @@ -0,0 +1,75 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/usage_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v1.0" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new c d r management API HTTP client. +func New(c Config) *CDRManagementAPI { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(CDRManagementAPI) + cli.Transport = transport + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + cli.UsageManagement = usage_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// CDRManagementAPI is a client for c d r management API +type CDRManagementAPI struct { + StatusManagement *status_management.Client + TriggerManagement *trigger_management.Client + UsageManagement *usage_management.Client + Transport runtime.ClientTransport +} diff --git a/services/cdr/client/status_management/get_status_parameters.go b/services/cdr/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..bc38256 --- /dev/null +++ b/services/cdr/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the endpoint to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/cdr/client/status_management/get_status_responses.go b/services/cdr/client/status_management/get_status_responses.go new file mode 100644 index 0000000..aac365c --- /dev/null +++ b/services/cdr/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/cdr/client/status_management/show_status_parameters.go b/services/cdr/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/services/cdr/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/cdr/client/status_management/show_status_responses.go b/services/cdr/client/status_management/show_status_responses.go new file mode 100644 index 0000000..fd2d520 --- /dev/null +++ b/services/cdr/client/status_management/show_status_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/cdr/client/status_management/status_management_client.go b/services/cdr/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/services/cdr/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/services/cdr/client/trigger_management/exec_transformation_parameters.go b/services/cdr/client/trigger_management/exec_transformation_parameters.go new file mode 100644 index 0000000..77165cb --- /dev/null +++ b/services/cdr/client/trigger_management/exec_transformation_parameters.go @@ -0,0 +1,211 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewExecTransformationParams creates a new ExecTransformationParams object +// with the default values initialized. +func NewExecTransformationParams() *ExecTransformationParams { + var () + return &ExecTransformationParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewExecTransformationParamsWithTimeout creates a new ExecTransformationParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewExecTransformationParamsWithTimeout(timeout time.Duration) *ExecTransformationParams { + var () + return &ExecTransformationParams{ + + timeout: timeout, + } +} + +// NewExecTransformationParamsWithContext creates a new ExecTransformationParams object +// with the default values initialized, and the ability to set a context for a request +func NewExecTransformationParamsWithContext(ctx context.Context) *ExecTransformationParams { + var () + return &ExecTransformationParams{ + + Context: ctx, + } +} + +// NewExecTransformationParamsWithHTTPClient creates a new ExecTransformationParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewExecTransformationParamsWithHTTPClient(client *http.Client) *ExecTransformationParams { + var () + return &ExecTransformationParams{ + HTTPClient: client, + } +} + +/*ExecTransformationParams contains all the parameters to send to the API endpoint +for the exec transformation operation typically these are written to a http.Request +*/ +type ExecTransformationParams struct { + + /*FastMode + Switch for using 15m boundaries instead of 8h + + */ + FastMode *bool + /*From + Datetime from which to get the usage report + + */ + From *strfmt.DateTime + /*To + Datetime until which to get the usage report + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the exec transformation params +func (o *ExecTransformationParams) WithTimeout(timeout time.Duration) *ExecTransformationParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the exec transformation params +func (o *ExecTransformationParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the exec transformation params +func (o *ExecTransformationParams) WithContext(ctx context.Context) *ExecTransformationParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the exec transformation params +func (o *ExecTransformationParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the exec transformation params +func (o *ExecTransformationParams) WithHTTPClient(client *http.Client) *ExecTransformationParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the exec transformation params +func (o *ExecTransformationParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFastMode adds the fastMode to the exec transformation params +func (o *ExecTransformationParams) WithFastMode(fastMode *bool) *ExecTransformationParams { + o.SetFastMode(fastMode) + return o +} + +// SetFastMode adds the fastMode to the exec transformation params +func (o *ExecTransformationParams) SetFastMode(fastMode *bool) { + o.FastMode = fastMode +} + +// WithFrom adds the from to the exec transformation params +func (o *ExecTransformationParams) WithFrom(from *strfmt.DateTime) *ExecTransformationParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the exec transformation params +func (o *ExecTransformationParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithTo adds the to to the exec transformation params +func (o *ExecTransformationParams) WithTo(to *strfmt.DateTime) *ExecTransformationParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the exec transformation params +func (o *ExecTransformationParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *ExecTransformationParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.FastMode != nil { + + // query param fast_mode + var qrFastMode bool + if o.FastMode != nil { + qrFastMode = *o.FastMode + } + qFastMode := swag.FormatBool(qrFastMode) + if qFastMode != "" { + if err := r.SetQueryParam("fast_mode", qFastMode); err != nil { + return err + } + } + + } + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/cdr/client/trigger_management/exec_transformation_responses.go b/services/cdr/client/trigger_management/exec_transformation_responses.go new file mode 100644 index 0000000..972c9cc --- /dev/null +++ b/services/cdr/client/trigger_management/exec_transformation_responses.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// ExecTransformationReader is a Reader for the ExecTransformation structure. +type ExecTransformationReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ExecTransformationReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewExecTransformationOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewExecTransformationInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewExecTransformationOK creates a ExecTransformationOK with default headers values +func NewExecTransformationOK() *ExecTransformationOK { + return &ExecTransformationOK{} +} + +/*ExecTransformationOK handles this case with default header values. + +Transformation task executed successfully. +*/ +type ExecTransformationOK struct { +} + +func (o *ExecTransformationOK) Error() string { + return fmt.Sprintf("[GET /trigger/transform][%d] execTransformationOK ", 200) +} + +func (o *ExecTransformationOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewExecTransformationInternalServerError creates a ExecTransformationInternalServerError with default headers values +func NewExecTransformationInternalServerError() *ExecTransformationInternalServerError { + return &ExecTransformationInternalServerError{} +} + +/*ExecTransformationInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ExecTransformationInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ExecTransformationInternalServerError) Error() string { + return fmt.Sprintf("[GET /trigger/transform][%d] execTransformationInternalServerError %+v", 500, o.Payload) +} + +func (o *ExecTransformationInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ExecTransformationInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/cdr/client/trigger_management/trigger_management_client.go b/services/cdr/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..9770e67 --- /dev/null +++ b/services/cdr/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + ExecTransformation transformations of u d r to c d r task trigger*/ + ExecTransformation(ctx context.Context, params *ExecTransformationParams) (*ExecTransformationOK, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +ExecTransformation transformations of u d r to c d r task trigger +*/ +func (a *Client) ExecTransformation(ctx context.Context, params *ExecTransformationParams) (*ExecTransformationOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "execTransformation", + Method: "GET", + PathPattern: "/trigger/transform", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ExecTransformationReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ExecTransformationOK), nil + +} diff --git a/services/cdr/client/usage_management/get_system_usage_parameters.go b/services/cdr/client/usage_management/get_system_usage_parameters.go new file mode 100644 index 0000000..2be27ed --- /dev/null +++ b/services/cdr/client/usage_management/get_system_usage_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSystemUsageParams creates a new GetSystemUsageParams object +// with the default values initialized. +func NewGetSystemUsageParams() *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSystemUsageParamsWithTimeout creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSystemUsageParamsWithTimeout(timeout time.Duration) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + timeout: timeout, + } +} + +// NewGetSystemUsageParamsWithContext creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSystemUsageParamsWithContext(ctx context.Context) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + Context: ctx, + } +} + +// NewGetSystemUsageParamsWithHTTPClient creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSystemUsageParamsWithHTTPClient(client *http.Client) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + HTTPClient: client, + } +} + +/*GetSystemUsageParams contains all the parameters to send to the API endpoint +for the get system usage operation typically these are written to a http.Request +*/ +type GetSystemUsageParams struct { + + /*From + Datetime from which to get the usage report + + */ + From *strfmt.DateTime + /*Idlist + List of ids to be queried + + */ + Idlist *string + /*Metric + Metric(s) to get the usage report + + */ + Metric *string + /*To + Datetime until which to get the usage report + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get system usage params +func (o *GetSystemUsageParams) WithTimeout(timeout time.Duration) *GetSystemUsageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get system usage params +func (o *GetSystemUsageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get system usage params +func (o *GetSystemUsageParams) WithContext(ctx context.Context) *GetSystemUsageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get system usage params +func (o *GetSystemUsageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get system usage params +func (o *GetSystemUsageParams) WithHTTPClient(client *http.Client) *GetSystemUsageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get system usage params +func (o *GetSystemUsageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get system usage params +func (o *GetSystemUsageParams) WithFrom(from *strfmt.DateTime) *GetSystemUsageParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get system usage params +func (o *GetSystemUsageParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithIdlist adds the idlist to the get system usage params +func (o *GetSystemUsageParams) WithIdlist(idlist *string) *GetSystemUsageParams { + o.SetIdlist(idlist) + return o +} + +// SetIdlist adds the idlist to the get system usage params +func (o *GetSystemUsageParams) SetIdlist(idlist *string) { + o.Idlist = idlist +} + +// WithMetric adds the metric to the get system usage params +func (o *GetSystemUsageParams) WithMetric(metric *string) *GetSystemUsageParams { + o.SetMetric(metric) + return o +} + +// SetMetric adds the metric to the get system usage params +func (o *GetSystemUsageParams) SetMetric(metric *string) { + o.Metric = metric +} + +// WithTo adds the to to the get system usage params +func (o *GetSystemUsageParams) WithTo(to *strfmt.DateTime) *GetSystemUsageParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get system usage params +func (o *GetSystemUsageParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSystemUsageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + if o.Idlist != nil { + + // query param idlist + var qrIdlist string + if o.Idlist != nil { + qrIdlist = *o.Idlist + } + qIdlist := qrIdlist + if qIdlist != "" { + if err := r.SetQueryParam("idlist", qIdlist); err != nil { + return err + } + } + + } + + if o.Metric != nil { + + // query param metric + var qrMetric string + if o.Metric != nil { + qrMetric = *o.Metric + } + qMetric := qrMetric + if qMetric != "" { + if err := r.SetQueryParam("metric", qMetric); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/cdr/client/usage_management/get_system_usage_responses.go b/services/cdr/client/usage_management/get_system_usage_responses.go new file mode 100644 index 0000000..89ca7d2 --- /dev/null +++ b/services/cdr/client/usage_management/get_system_usage_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetSystemUsageReader is a Reader for the GetSystemUsage structure. +type GetSystemUsageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSystemUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSystemUsageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewGetSystemUsageInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetSystemUsageOK creates a GetSystemUsageOK with default headers values +func NewGetSystemUsageOK() *GetSystemUsageOK { + return &GetSystemUsageOK{} +} + +/*GetSystemUsageOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetSystemUsageOK struct { + Payload []*models.CReport +} + +func (o *GetSystemUsageOK) Error() string { + return fmt.Sprintf("[GET /usage][%d] getSystemUsageOK %+v", 200, o.Payload) +} + +func (o *GetSystemUsageOK) GetPayload() []*models.CReport { + return o.Payload +} + +func (o *GetSystemUsageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSystemUsageInternalServerError creates a GetSystemUsageInternalServerError with default headers values +func NewGetSystemUsageInternalServerError() *GetSystemUsageInternalServerError { + return &GetSystemUsageInternalServerError{} +} + +/*GetSystemUsageInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetSystemUsageInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetSystemUsageInternalServerError) Error() string { + return fmt.Sprintf("[GET /usage][%d] getSystemUsageInternalServerError %+v", 500, o.Payload) +} + +func (o *GetSystemUsageInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSystemUsageInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/cdr/client/usage_management/get_usage_parameters.go b/services/cdr/client/usage_management/get_usage_parameters.go new file mode 100644 index 0000000..a070629 --- /dev/null +++ b/services/cdr/client/usage_management/get_usage_parameters.go @@ -0,0 +1,231 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetUsageParams creates a new GetUsageParams object +// with the default values initialized. +func NewGetUsageParams() *GetUsageParams { + var () + return &GetUsageParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetUsageParamsWithTimeout creates a new GetUsageParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetUsageParamsWithTimeout(timeout time.Duration) *GetUsageParams { + var () + return &GetUsageParams{ + + timeout: timeout, + } +} + +// NewGetUsageParamsWithContext creates a new GetUsageParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetUsageParamsWithContext(ctx context.Context) *GetUsageParams { + var () + return &GetUsageParams{ + + Context: ctx, + } +} + +// NewGetUsageParamsWithHTTPClient creates a new GetUsageParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetUsageParamsWithHTTPClient(client *http.Client) *GetUsageParams { + var () + return &GetUsageParams{ + HTTPClient: client, + } +} + +/*GetUsageParams contains all the parameters to send to the API endpoint +for the get usage operation typically these are written to a http.Request +*/ +type GetUsageParams struct { + + /*From + Datetime from which to get the usage report + + */ + From *strfmt.DateTime + /*ID + Id of the account to be checked + + */ + ID string + /*Metric + Metric(s) to get the usage report + + */ + Metric *string + /*To + Datetime until which to get the usage report + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get usage params +func (o *GetUsageParams) WithTimeout(timeout time.Duration) *GetUsageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get usage params +func (o *GetUsageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get usage params +func (o *GetUsageParams) WithContext(ctx context.Context) *GetUsageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get usage params +func (o *GetUsageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get usage params +func (o *GetUsageParams) WithHTTPClient(client *http.Client) *GetUsageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get usage params +func (o *GetUsageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get usage params +func (o *GetUsageParams) WithFrom(from *strfmt.DateTime) *GetUsageParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get usage params +func (o *GetUsageParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithID adds the id to the get usage params +func (o *GetUsageParams) WithID(id string) *GetUsageParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get usage params +func (o *GetUsageParams) SetID(id string) { + o.ID = id +} + +// WithMetric adds the metric to the get usage params +func (o *GetUsageParams) WithMetric(metric *string) *GetUsageParams { + o.SetMetric(metric) + return o +} + +// SetMetric adds the metric to the get usage params +func (o *GetUsageParams) SetMetric(metric *string) { + o.Metric = metric +} + +// WithTo adds the to to the get usage params +func (o *GetUsageParams) WithTo(to *strfmt.DateTime) *GetUsageParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get usage params +func (o *GetUsageParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetUsageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Metric != nil { + + // query param metric + var qrMetric string + if o.Metric != nil { + qrMetric = *o.Metric + } + qMetric := qrMetric + if qMetric != "" { + if err := r.SetQueryParam("metric", qMetric); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/cdr/client/usage_management/get_usage_responses.go b/services/cdr/client/usage_management/get_usage_responses.go new file mode 100644 index 0000000..d71fa99 --- /dev/null +++ b/services/cdr/client/usage_management/get_usage_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetUsageReader is a Reader for the GetUsage structure. +type GetUsageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetUsageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewGetUsageInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetUsageOK creates a GetUsageOK with default headers values +func NewGetUsageOK() *GetUsageOK { + return &GetUsageOK{} +} + +/*GetUsageOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetUsageOK struct { + Payload []*models.CReport +} + +func (o *GetUsageOK) Error() string { + return fmt.Sprintf("[GET /usage/{id}][%d] getUsageOK %+v", 200, o.Payload) +} + +func (o *GetUsageOK) GetPayload() []*models.CReport { + return o.Payload +} + +func (o *GetUsageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetUsageInternalServerError creates a GetUsageInternalServerError with default headers values +func NewGetUsageInternalServerError() *GetUsageInternalServerError { + return &GetUsageInternalServerError{} +} + +/*GetUsageInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetUsageInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetUsageInternalServerError) Error() string { + return fmt.Sprintf("[GET /usage/{id}][%d] getUsageInternalServerError %+v", 500, o.Payload) +} + +func (o *GetUsageInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetUsageInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/cdr/client/usage_management/get_usage_summary_parameters.go b/services/cdr/client/usage_management/get_usage_summary_parameters.go new file mode 100644 index 0000000..7fdd212 --- /dev/null +++ b/services/cdr/client/usage_management/get_usage_summary_parameters.go @@ -0,0 +1,199 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetUsageSummaryParams creates a new GetUsageSummaryParams object +// with the default values initialized. +func NewGetUsageSummaryParams() *GetUsageSummaryParams { + var () + return &GetUsageSummaryParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetUsageSummaryParamsWithTimeout creates a new GetUsageSummaryParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetUsageSummaryParamsWithTimeout(timeout time.Duration) *GetUsageSummaryParams { + var () + return &GetUsageSummaryParams{ + + timeout: timeout, + } +} + +// NewGetUsageSummaryParamsWithContext creates a new GetUsageSummaryParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetUsageSummaryParamsWithContext(ctx context.Context) *GetUsageSummaryParams { + var () + return &GetUsageSummaryParams{ + + Context: ctx, + } +} + +// NewGetUsageSummaryParamsWithHTTPClient creates a new GetUsageSummaryParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetUsageSummaryParamsWithHTTPClient(client *http.Client) *GetUsageSummaryParams { + var () + return &GetUsageSummaryParams{ + HTTPClient: client, + } +} + +/*GetUsageSummaryParams contains all the parameters to send to the API endpoint +for the get usage summary operation typically these are written to a http.Request +*/ +type GetUsageSummaryParams struct { + + /*From + Datetime from which to get the usage report + + */ + From *strfmt.DateTime + /*ID + Id of the reseller to be checked + + */ + ID string + /*To + Datetime until which to get the usage report + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get usage summary params +func (o *GetUsageSummaryParams) WithTimeout(timeout time.Duration) *GetUsageSummaryParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get usage summary params +func (o *GetUsageSummaryParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get usage summary params +func (o *GetUsageSummaryParams) WithContext(ctx context.Context) *GetUsageSummaryParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get usage summary params +func (o *GetUsageSummaryParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get usage summary params +func (o *GetUsageSummaryParams) WithHTTPClient(client *http.Client) *GetUsageSummaryParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get usage summary params +func (o *GetUsageSummaryParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get usage summary params +func (o *GetUsageSummaryParams) WithFrom(from *strfmt.DateTime) *GetUsageSummaryParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get usage summary params +func (o *GetUsageSummaryParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithID adds the id to the get usage summary params +func (o *GetUsageSummaryParams) WithID(id string) *GetUsageSummaryParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get usage summary params +func (o *GetUsageSummaryParams) SetID(id string) { + o.ID = id +} + +// WithTo adds the to to the get usage summary params +func (o *GetUsageSummaryParams) WithTo(to *strfmt.DateTime) *GetUsageSummaryParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get usage summary params +func (o *GetUsageSummaryParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetUsageSummaryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/cdr/client/usage_management/get_usage_summary_responses.go b/services/cdr/client/usage_management/get_usage_summary_responses.go new file mode 100644 index 0000000..a180325 --- /dev/null +++ b/services/cdr/client/usage_management/get_usage_summary_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetUsageSummaryReader is a Reader for the GetUsageSummary structure. +type GetUsageSummaryReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetUsageSummaryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetUsageSummaryOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewGetUsageSummaryInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetUsageSummaryOK creates a GetUsageSummaryOK with default headers values +func NewGetUsageSummaryOK() *GetUsageSummaryOK { + return &GetUsageSummaryOK{} +} + +/*GetUsageSummaryOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetUsageSummaryOK struct { + Payload *models.UISummary +} + +func (o *GetUsageSummaryOK) Error() string { + return fmt.Sprintf("[GET /usage/summary/{id}][%d] getUsageSummaryOK %+v", 200, o.Payload) +} + +func (o *GetUsageSummaryOK) GetPayload() *models.UISummary { + return o.Payload +} + +func (o *GetUsageSummaryOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.UISummary) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetUsageSummaryInternalServerError creates a GetUsageSummaryInternalServerError with default headers values +func NewGetUsageSummaryInternalServerError() *GetUsageSummaryInternalServerError { + return &GetUsageSummaryInternalServerError{} +} + +/*GetUsageSummaryInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetUsageSummaryInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetUsageSummaryInternalServerError) Error() string { + return fmt.Sprintf("[GET /usage/summary/{id}][%d] getUsageSummaryInternalServerError %+v", 500, o.Payload) +} + +func (o *GetUsageSummaryInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetUsageSummaryInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/cdr/client/usage_management/usage_management_client.go b/services/cdr/client/usage_management/usage_management_client.go new file mode 100644 index 0000000..1392638 --- /dev/null +++ b/services/cdr/client/usage_management/usage_management_client.go @@ -0,0 +1,122 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the usage management client +type API interface { + /* + GetSystemUsage detaileds report covering all accounts within the specified time window*/ + GetSystemUsage(ctx context.Context, params *GetSystemUsageParams) (*GetSystemUsageOK, error) + /* + GetUsage detaileds report covering of the account associated with the id within the specified time window*/ + GetUsage(ctx context.Context, params *GetUsageParams) (*GetUsageOK, error) + /* + GetUsageSummary summaries report meant for the UI for the resources linked to the reseller ID provided within the specified time window*/ + GetUsageSummary(ctx context.Context, params *GetUsageSummaryParams) (*GetUsageSummaryOK, error) +} + +// New creates a new usage management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for usage management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetSystemUsage detaileds report covering all accounts within the specified time window +*/ +func (a *Client) GetSystemUsage(ctx context.Context, params *GetSystemUsageParams) (*GetSystemUsageOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSystemUsage", + Method: "GET", + PathPattern: "/usage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSystemUsageReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSystemUsageOK), nil + +} + +/* +GetUsage detaileds report covering of the account associated with the id within the specified time window +*/ +func (a *Client) GetUsage(ctx context.Context, params *GetUsageParams) (*GetUsageOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getUsage", + Method: "GET", + PathPattern: "/usage/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetUsageReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetUsageOK), nil + +} + +/* +GetUsageSummary summaries report meant for the UI for the resources linked to the reseller ID provided within the specified time window +*/ +func (a *Client) GetUsageSummary(ctx context.Context, params *GetUsageSummaryParams) (*GetUsageSummaryOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getUsageSummary", + Method: "GET", + PathPattern: "/usage/summary/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetUsageSummaryReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetUsageSummaryOK), nil + +} diff --git a/services/cdr/go.mod b/services/cdr/go.mod new file mode 100644 index 0000000..37ecc15 --- /dev/null +++ b/services/cdr/go.mod @@ -0,0 +1,28 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr + +go 1.15 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/prometheus/client_golang v1.11.0 + github.com/remeh/sizedwaitgroup v1.0.0 + github.com/rs/cors v1.8.2 + github.com/segmentio/asm v1.1.3 // indirect + github.com/segmentio/encoding v0.3.2 + github.com/segmentio/kafka-go v0.4.25 + github.com/spf13/viper v1.10.1 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/services/cdr/models/c_d_r_record.go b/services/cdr/models/c_d_r_record.go new file mode 100644 index 0000000..2fb9640 --- /dev/null +++ b/services/cdr/models/c_d_r_record.go @@ -0,0 +1,114 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// CDRRecord c d r record +// +// swagger:model CDRRecord +type CDRRecord struct { + + // account Id + AccountID string `json:"AccountId,omitempty" gorm:"index"` + + // cost + Cost datamodels.JSONdb `json:"Cost,omitempty" gorm:"type:jsonb"` + + // metadata + Metadata datamodels.JSONdb `json:"Metadata,omitempty" gorm:"type:jsonb"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // time from + // Format: datetime + TimeFrom strfmt.DateTime `json:"TimeFrom,omitempty" gorm:"index;type:timestamptz"` + + // time to + // Format: datetime + TimeTo strfmt.DateTime `json:"TimeTo,omitempty" gorm:"index;type:timestamptz"` + + // unit + Unit string `json:"Unit,omitempty"` + + // usage breakup + UsageBreakup datamodels.JSONdb `json:"UsageBreakup,omitempty" gorm:"type:jsonb"` +} + +// Validate validates this c d r record +func (m *CDRRecord) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTimeFrom(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimeTo(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CDRRecord) validateTimeFrom(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeFrom) { // not required + return nil + } + + if err := validate.FormatOf("TimeFrom", "body", "datetime", m.TimeFrom.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *CDRRecord) validateTimeTo(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeTo) { // not required + return nil + } + + if err := validate.FormatOf("TimeTo", "body", "datetime", m.TimeTo.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CDRRecord) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CDRRecord) UnmarshalBinary(b []byte) error { + var res CDRRecord + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/cdr/models/c_d_r_report.go b/services/cdr/models/c_d_r_report.go new file mode 100644 index 0000000..0cfadf5 --- /dev/null +++ b/services/cdr/models/c_d_r_report.go @@ -0,0 +1,62 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "gitlab.com/cyclops-utilities/datamodels" +) + +// CDRReport c d r report +// +// swagger:model CDRReport +type CDRReport struct { + + // cost + Cost datamodels.JSONdb `json:"Cost,omitempty" gorm:"type:jsonb"` + + // metadata + Metadata datamodels.JSONdb `json:"Metadata,omitempty" gorm:"type:jsonb"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // unit + Unit string `json:"Unit,omitempty"` + + // usage breakup + UsageBreakup datamodels.JSONdb `json:"UsageBreakup,omitempty" gorm:"type:jsonb"` +} + +// Validate validates this c d r report +func (m *CDRReport) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CDRReport) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CDRReport) UnmarshalBinary(b []byte) error { + var res CDRReport + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/cdr/models/c_report.go b/services/cdr/models/c_report.go new file mode 100644 index 0000000..8bf5387 --- /dev/null +++ b/services/cdr/models/c_report.go @@ -0,0 +1,126 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CReport c report +// +// swagger:model CReport +type CReport struct { + + // account Id + AccountID string `json:"AccountId,omitempty" gorm:"index"` + + // time from + // Format: datetime + TimeFrom strfmt.DateTime `json:"TimeFrom,omitempty" gorm:"index;type:timestamptz"` + + // time to + // Format: datetime + TimeTo strfmt.DateTime `json:"TimeTo,omitempty" gorm:"index;type:timestamptz"` + + // usage + Usage []*CDRReport `json:"Usage" gorm:"-"` +} + +// Validate validates this c report +func (m *CReport) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTimeFrom(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimeTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUsage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CReport) validateTimeFrom(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeFrom) { // not required + return nil + } + + if err := validate.FormatOf("TimeFrom", "body", "datetime", m.TimeFrom.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *CReport) validateTimeTo(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeTo) { // not required + return nil + } + + if err := validate.FormatOf("TimeTo", "body", "datetime", m.TimeTo.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *CReport) validateUsage(formats strfmt.Registry) error { + + if swag.IsZero(m.Usage) { // not required + return nil + } + + for i := 0; i < len(m.Usage); i++ { + if swag.IsZero(m.Usage[i]) { // not required + continue + } + + if m.Usage[i] != nil { + if err := m.Usage[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("Usage" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CReport) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CReport) UnmarshalBinary(b []byte) error { + var res CReport + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/cdr/models/error_response.go b/services/cdr/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/services/cdr/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/cdr/models/item_created_response.go b/services/cdr/models/item_created_response.go new file mode 100644 index 0000000..ea34934 --- /dev/null +++ b/services/cdr/models/item_created_response.go @@ -0,0 +1,46 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ItemCreatedResponse item created response +// +// swagger:model ItemCreatedResponse +type ItemCreatedResponse struct { + + // Api link + APILink string `json:"ApiLink,omitempty"` + + // message + Message string `json:"Message,omitempty"` +} + +// Validate validates this item created response +func (m *ItemCreatedResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ItemCreatedResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ItemCreatedResponse) UnmarshalBinary(b []byte) error { + var res ItemCreatedResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/cdr/models/status.go b/services/cdr/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/services/cdr/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/cdr/models/ui_summary.go b/services/cdr/models/ui_summary.go new file mode 100644 index 0000000..756ed21 --- /dev/null +++ b/services/cdr/models/ui_summary.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// UISummary UI summary +// +// swagger:model UISummary +type UISummary struct { + + // account Id + AccountID string `json:"AccountId,omitempty"` + + // time from + // Format: datetime + TimeFrom strfmt.DateTime `json:"TimeFrom,omitempty"` + + // time to + // Format: datetime + TimeTo strfmt.DateTime `json:"TimeTo,omitempty"` + + // usage breakup + UsageBreakup datamodels.JSONdb `json:"UsageBreakup,omitempty"` +} + +// Validate validates this UI summary +func (m *UISummary) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTimeFrom(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimeTo(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UISummary) validateTimeFrom(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeFrom) { // not required + return nil + } + + if err := validate.FormatOf("TimeFrom", "body", "datetime", m.TimeFrom.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *UISummary) validateTimeTo(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeTo) { // not required + return nil + } + + if err := validate.FormatOf("TimeTo", "body", "datetime", m.TimeTo.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UISummary) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UISummary) UnmarshalBinary(b []byte) error { + var res UISummary + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/cdr/restapi/configure_c_d_r_management_api.go b/services/cdr/restapi/configure_c_d_r_management_api.go new file mode 100644 index 0000000..e8001de --- /dev/null +++ b/services/cdr/restapi/configure_c_d_r_management_api.go @@ -0,0 +1,196 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/usage_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* ExecTransformation Transformation of UDR to CDR task trigger */ + ExecTransformation(ctx context.Context, params trigger_management.ExecTransformationParams) middleware.Responder +} + +//go:generate mockery -name UsageManagementAPI -inpkg + +/* UsageManagementAPI */ +type UsageManagementAPI interface { + /* GetSystemUsage Detailed report covering all accounts within the specified time window */ + GetSystemUsage(ctx context.Context, params usage_management.GetSystemUsageParams) middleware.Responder + + /* GetUsage Detailed report covering of the account associated with the id within the specified time window */ + GetUsage(ctx context.Context, params usage_management.GetUsageParams) middleware.Responder + + /* GetUsageSummary Summary report meant for the UI for the resources linked to the ResellerID provided within the specified time window */ + GetUsageSummary(ctx context.Context, params usage_management.GetUsageSummaryParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + StatusManagementAPI + TriggerManagementAPI + UsageManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) + // Authenticator to use for all APIKey authentication + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // Authenticator to use for all Bearer authentication + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // Authenticator to use for all Basic authentication + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *CDRManagementAPI instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.CDRManagementAPIAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewCDRManagementAPIAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + if c.APIKeyAuthenticator != nil { + api.APIKeyAuthenticator = c.APIKeyAuthenticator + } + if c.BasicAuthenticator != nil { + api.BasicAuthenticator = c.BasicAuthenticator + } + if c.BearerAuthenticator != nil { + api.BearerAuthenticator = c.BearerAuthenticator + } + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.TriggerManagementExecTransformationHandler = trigger_management.ExecTransformationHandlerFunc(func(params trigger_management.ExecTransformationParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.ExecTransformation(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.UsageManagementGetSystemUsageHandler = usage_management.GetSystemUsageHandlerFunc(func(params usage_management.GetSystemUsageParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.UsageManagementAPI.GetSystemUsage(ctx, params) + }) + api.UsageManagementGetUsageHandler = usage_management.GetUsageHandlerFunc(func(params usage_management.GetUsageParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.UsageManagementAPI.GetUsage(ctx, params) + }) + api.UsageManagementGetUsageSummaryHandler = usage_management.GetUsageSummaryHandlerFunc(func(params usage_management.GetUsageSummaryParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.UsageManagementAPI.GetUsageSummary(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/services/cdr/restapi/doc.go b/services/cdr/restapi/doc.go new file mode 100644 index 0000000..1d5b034 --- /dev/null +++ b/services/cdr/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi CDR Management API +// +// An API which supports creation, deletion, listing etc of CDR +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v1.0 +// Version: 1.0.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/services/cdr/restapi/embedded_spec.go b/services/cdr/restapi/embedded_spec.go new file mode 100644 index 0000000..2b12766 --- /dev/null +++ b/services/cdr/restapi/embedded_spec.go @@ -0,0 +1,1222 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of CDR", + "title": "CDR Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "usage" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/transform": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Transformation of UDR to CDR task trigger", + "operationId": "execTransformation", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "boolean", + "description": "Switch for using 15m boundaries instead of 8h", + "name": "fast_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Transformation task executed successfully." + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering all accounts within the specified time window", + "operationId": "getSystemUsage", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + }, + { + "type": "string", + "description": "List of ids to be queried", + "name": "idlist", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/CReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/summary/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Summary report meant for the UI for the resources linked to the ResellerID provided within the specified time window", + "operationId": "getUsageSummary", + "parameters": [ + { + "type": "string", + "description": "Id of the reseller to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/UISummary" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering of the account associated with the id within the specified time window", + "operationId": "getUsage", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/CReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "CDRRecord": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "Cost": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "CDRReport": { + "type": "object", + "properties": { + "Cost": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "CReport": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Usage": { + "type": "array", + "items": { + "$ref": "#/definitions/CDRReport" + }, + "x-go-custom-tag": "gorm:\"-\"" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "UISummary": { + "type": "object", + "properties": { + "AccountId": { + "type": "string" + }, + "TimeFrom": { + "type": "string", + "format": "datetime" + }, + "TimeTo": { + "type": "string", + "format": "datetime" + }, + "UsageBreakup": { + "$ref": "#/definitions/Metadata" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the usage reporting of the accounts of the system", + "name": "usageManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of CDR", + "title": "CDR Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "usage" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/transform": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Transformation of UDR to CDR task trigger", + "operationId": "execTransformation", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "boolean", + "description": "Switch for using 15m boundaries instead of 8h", + "name": "fast_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Transformation task executed successfully." + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering all accounts within the specified time window", + "operationId": "getSystemUsage", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + }, + { + "type": "string", + "description": "List of ids to be queried", + "name": "idlist", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/CReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/summary/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Summary report meant for the UI for the resources linked to the ResellerID provided within the specified time window", + "operationId": "getUsageSummary", + "parameters": [ + { + "type": "string", + "description": "Id of the reseller to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/UISummary" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering of the account associated with the id within the specified time window", + "operationId": "getUsage", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/CReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "CDRRecord": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "Cost": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "CDRReport": { + "type": "object", + "properties": { + "Cost": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "CReport": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Usage": { + "type": "array", + "items": { + "$ref": "#/definitions/CDRReport" + }, + "x-go-custom-tag": "gorm:\"-\"" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "UISummary": { + "type": "object", + "properties": { + "AccountId": { + "type": "string" + }, + "TimeFrom": { + "type": "string", + "format": "datetime" + }, + "TimeTo": { + "type": "string", + "format": "datetime" + }, + "UsageBreakup": { + "$ref": "#/definitions/Metadata" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the usage reporting of the accounts of the system", + "name": "usageManagement" + } + ] +}`)) +} diff --git a/services/cdr/restapi/operations/c_d_r_management_api_api.go b/services/cdr/restapi/operations/c_d_r_management_api_api.go new file mode 100644 index 0000000..08ed686 --- /dev/null +++ b/services/cdr/restapi/operations/c_d_r_management_api_api.go @@ -0,0 +1,417 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/usage_management" +) + +// NewCDRManagementAPIAPI creates a new CDRManagementAPI instance +func NewCDRManagementAPIAPI(spec *loads.Document) *CDRManagementAPIAPI { + return &CDRManagementAPIAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + useSwaggerUI: false, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + TriggerManagementExecTransformationHandler: trigger_management.ExecTransformationHandlerFunc(func(params trigger_management.ExecTransformationParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.ExecTransformation has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + UsageManagementGetSystemUsageHandler: usage_management.GetSystemUsageHandlerFunc(func(params usage_management.GetSystemUsageParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation usage_management.GetSystemUsage has not yet been implemented") + }), + UsageManagementGetUsageHandler: usage_management.GetUsageHandlerFunc(func(params usage_management.GetUsageParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation usage_management.GetUsage has not yet been implemented") + }), + UsageManagementGetUsageSummaryHandler: usage_management.GetUsageSummaryHandlerFunc(func(params usage_management.GetUsageSummaryParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation usage_management.GetUsageSummary has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*CDRManagementAPIAPI An API which supports creation, deletion, listing etc of CDR */ +type CDRManagementAPIAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + useSwaggerUI bool + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // TriggerManagementExecTransformationHandler sets the operation handler for the exec transformation operation + TriggerManagementExecTransformationHandler trigger_management.ExecTransformationHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // UsageManagementGetSystemUsageHandler sets the operation handler for the get system usage operation + UsageManagementGetSystemUsageHandler usage_management.GetSystemUsageHandler + // UsageManagementGetUsageHandler sets the operation handler for the get usage operation + UsageManagementGetUsageHandler usage_management.GetUsageHandler + // UsageManagementGetUsageSummaryHandler sets the operation handler for the get usage summary operation + UsageManagementGetUsageSummaryHandler usage_management.GetUsageSummaryHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// UseRedoc for documentation at /docs +func (o *CDRManagementAPIAPI) UseRedoc() { + o.useSwaggerUI = false +} + +// UseSwaggerUI for documentation at /docs +func (o *CDRManagementAPIAPI) UseSwaggerUI() { + o.useSwaggerUI = true +} + +// SetDefaultProduces sets the default produces media type +func (o *CDRManagementAPIAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *CDRManagementAPIAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *CDRManagementAPIAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *CDRManagementAPIAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *CDRManagementAPIAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *CDRManagementAPIAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *CDRManagementAPIAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the CDRManagementAPIAPI +func (o *CDRManagementAPIAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.TriggerManagementExecTransformationHandler == nil { + unregistered = append(unregistered, "trigger_management.ExecTransformationHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.UsageManagementGetSystemUsageHandler == nil { + unregistered = append(unregistered, "usage_management.GetSystemUsageHandler") + } + if o.UsageManagementGetUsageHandler == nil { + unregistered = append(unregistered, "usage_management.GetUsageHandler") + } + if o.UsageManagementGetUsageSummaryHandler == nil { + unregistered = append(unregistered, "usage_management.GetUsageSummaryHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *CDRManagementAPIAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *CDRManagementAPIAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *CDRManagementAPIAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *CDRManagementAPIAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *CDRManagementAPIAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *CDRManagementAPIAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the c d r management API API +func (o *CDRManagementAPIAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *CDRManagementAPIAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/transform"] = trigger_management.NewExecTransformation(o.context, o.TriggerManagementExecTransformationHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/usage"] = usage_management.NewGetSystemUsage(o.context, o.UsageManagementGetSystemUsageHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/usage/{id}"] = usage_management.NewGetUsage(o.context, o.UsageManagementGetUsageHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/usage/summary/{id}"] = usage_management.NewGetUsageSummary(o.context, o.UsageManagementGetUsageSummaryHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *CDRManagementAPIAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + if o.useSwaggerUI { + return o.context.APIHandlerSwaggerUI(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *CDRManagementAPIAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *CDRManagementAPIAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *CDRManagementAPIAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *CDRManagementAPIAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/services/cdr/restapi/operations/status_management/get_status.go b/services/cdr/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/services/cdr/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/cdr/restapi/operations/status_management/get_status_parameters.go b/services/cdr/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..aad73c8 --- /dev/null +++ b/services/cdr/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the endpoint to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"kafka-receiver", "kafka-sender", "status", "trigger", "usage"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/cdr/restapi/operations/status_management/get_status_responses.go b/services/cdr/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..48e848c --- /dev/null +++ b/services/cdr/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/cdr/restapi/operations/status_management/get_status_urlbuilder.go b/services/cdr/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..151ece5 --- /dev/null +++ b/services/cdr/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/cdr/restapi/operations/status_management/show_status.go b/services/cdr/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/services/cdr/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/cdr/restapi/operations/status_management/show_status_parameters.go b/services/cdr/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/services/cdr/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/cdr/restapi/operations/status_management/show_status_responses.go b/services/cdr/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..8b77a1a --- /dev/null +++ b/services/cdr/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/cdr/restapi/operations/status_management/show_status_urlbuilder.go b/services/cdr/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..6efc165 --- /dev/null +++ b/services/cdr/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/cdr/restapi/operations/trigger_management/exec_transformation.go b/services/cdr/restapi/operations/trigger_management/exec_transformation.go new file mode 100644 index 0000000..eabbc03 --- /dev/null +++ b/services/cdr/restapi/operations/trigger_management/exec_transformation.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ExecTransformationHandlerFunc turns a function with the right signature into a exec transformation handler +type ExecTransformationHandlerFunc func(ExecTransformationParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ExecTransformationHandlerFunc) Handle(params ExecTransformationParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ExecTransformationHandler interface for that can handle valid exec transformation params +type ExecTransformationHandler interface { + Handle(ExecTransformationParams, interface{}) middleware.Responder +} + +// NewExecTransformation creates a new http.Handler for the exec transformation operation +func NewExecTransformation(ctx *middleware.Context, handler ExecTransformationHandler) *ExecTransformation { + return &ExecTransformation{Context: ctx, Handler: handler} +} + +/*ExecTransformation swagger:route GET /trigger/transform triggerManagement execTransformation + +Transformation of UDR to CDR task trigger + +*/ +type ExecTransformation struct { + Context *middleware.Context + Handler ExecTransformationHandler +} + +func (o *ExecTransformation) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewExecTransformationParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/cdr/restapi/operations/trigger_management/exec_transformation_parameters.go b/services/cdr/restapi/operations/trigger_management/exec_transformation_parameters.go new file mode 100644 index 0000000..c1a7db4 --- /dev/null +++ b/services/cdr/restapi/operations/trigger_management/exec_transformation_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// NewExecTransformationParams creates a new ExecTransformationParams object +// no default values defined in spec. +func NewExecTransformationParams() ExecTransformationParams { + + return ExecTransformationParams{} +} + +// ExecTransformationParams contains all the bound params for the exec transformation operation +// typically these are obtained from a http.Request +// +// swagger:parameters execTransformation +type ExecTransformationParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Switch for using 15m boundaries instead of 8h + In: query + */ + FastMode *bool + /*Datetime from which to get the usage report + In: query + */ + From *strfmt.DateTime + /*Datetime until which to get the usage report + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewExecTransformationParams() beforehand. +func (o *ExecTransformationParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFastMode, qhkFastMode, _ := qs.GetOK("fast_mode") + if err := o.bindFastMode(qFastMode, qhkFastMode, route.Formats); err != nil { + res = append(res, err) + } + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFastMode binds and validates parameter FastMode from query. +func (o *ExecTransformationParams) bindFastMode(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertBool(raw) + if err != nil { + return errors.InvalidType("fast_mode", "query", "bool", raw) + } + o.FastMode = &value + + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *ExecTransformationParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *ExecTransformationParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *ExecTransformationParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *ExecTransformationParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/cdr/restapi/operations/trigger_management/exec_transformation_responses.go b/services/cdr/restapi/operations/trigger_management/exec_transformation_responses.go new file mode 100644 index 0000000..b7dfa91 --- /dev/null +++ b/services/cdr/restapi/operations/trigger_management/exec_transformation_responses.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// ExecTransformationOKCode is the HTTP code returned for type ExecTransformationOK +const ExecTransformationOKCode int = 200 + +/*ExecTransformationOK Transformation task executed successfully. + +swagger:response execTransformationOK +*/ +type ExecTransformationOK struct { +} + +// NewExecTransformationOK creates ExecTransformationOK with default headers values +func NewExecTransformationOK() *ExecTransformationOK { + + return &ExecTransformationOK{} +} + +// WriteResponse to the client +func (o *ExecTransformationOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// ExecTransformationInternalServerErrorCode is the HTTP code returned for type ExecTransformationInternalServerError +const ExecTransformationInternalServerErrorCode int = 500 + +/*ExecTransformationInternalServerError Something unexpected happend, error raised + +swagger:response execTransformationInternalServerError +*/ +type ExecTransformationInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewExecTransformationInternalServerError creates ExecTransformationInternalServerError with default headers values +func NewExecTransformationInternalServerError() *ExecTransformationInternalServerError { + + return &ExecTransformationInternalServerError{} +} + +// WithPayload adds the payload to the exec transformation internal server error response +func (o *ExecTransformationInternalServerError) WithPayload(payload *models.ErrorResponse) *ExecTransformationInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the exec transformation internal server error response +func (o *ExecTransformationInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ExecTransformationInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/cdr/restapi/operations/trigger_management/exec_transformation_urlbuilder.go b/services/cdr/restapi/operations/trigger_management/exec_transformation_urlbuilder.go new file mode 100644 index 0000000..cbd7329 --- /dev/null +++ b/services/cdr/restapi/operations/trigger_management/exec_transformation_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ExecTransformationURL generates an URL for the exec transformation operation +type ExecTransformationURL struct { + FastMode *bool + From *strfmt.DateTime + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecTransformationURL) WithBasePath(bp string) *ExecTransformationURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecTransformationURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ExecTransformationURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/transform" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fastModeQ string + if o.FastMode != nil { + fastModeQ = swag.FormatBool(*o.FastMode) + } + if fastModeQ != "" { + qs.Set("fast_mode", fastModeQ) + } + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ExecTransformationURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ExecTransformationURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ExecTransformationURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ExecTransformationURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ExecTransformationURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ExecTransformationURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/cdr/restapi/operations/usage_management/get_system_usage.go b/services/cdr/restapi/operations/usage_management/get_system_usage.go new file mode 100644 index 0000000..fed7a73 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_system_usage.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetSystemUsageHandlerFunc turns a function with the right signature into a get system usage handler +type GetSystemUsageHandlerFunc func(GetSystemUsageParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetSystemUsageHandlerFunc) Handle(params GetSystemUsageParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetSystemUsageHandler interface for that can handle valid get system usage params +type GetSystemUsageHandler interface { + Handle(GetSystemUsageParams, interface{}) middleware.Responder +} + +// NewGetSystemUsage creates a new http.Handler for the get system usage operation +func NewGetSystemUsage(ctx *middleware.Context, handler GetSystemUsageHandler) *GetSystemUsage { + return &GetSystemUsage{Context: ctx, Handler: handler} +} + +/*GetSystemUsage swagger:route GET /usage usageManagement getSystemUsage + +Detailed report covering all accounts within the specified time window + +*/ +type GetSystemUsage struct { + Context *middleware.Context + Handler GetSystemUsageHandler +} + +func (o *GetSystemUsage) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetSystemUsageParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/cdr/restapi/operations/usage_management/get_system_usage_parameters.go b/services/cdr/restapi/operations/usage_management/get_system_usage_parameters.go new file mode 100644 index 0000000..b649605 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_system_usage_parameters.go @@ -0,0 +1,195 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetSystemUsageParams creates a new GetSystemUsageParams object +// no default values defined in spec. +func NewGetSystemUsageParams() GetSystemUsageParams { + + return GetSystemUsageParams{} +} + +// GetSystemUsageParams contains all the bound params for the get system usage operation +// typically these are obtained from a http.Request +// +// swagger:parameters getSystemUsage +type GetSystemUsageParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to get the usage report + In: query + */ + From *strfmt.DateTime + /*List of ids to be queried + In: query + */ + Idlist *string + /*Metric(s) to get the usage report + In: query + */ + Metric *string + /*Datetime until which to get the usage report + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetSystemUsageParams() beforehand. +func (o *GetSystemUsageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + qIdlist, qhkIdlist, _ := qs.GetOK("idlist") + if err := o.bindIdlist(qIdlist, qhkIdlist, route.Formats); err != nil { + res = append(res, err) + } + + qMetric, qhkMetric, _ := qs.GetOK("metric") + if err := o.bindMetric(qMetric, qhkMetric, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetSystemUsageParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *GetSystemUsageParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindIdlist binds and validates parameter Idlist from query. +func (o *GetSystemUsageParams) bindIdlist(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Idlist = &raw + + return nil +} + +// bindMetric binds and validates parameter Metric from query. +func (o *GetSystemUsageParams) bindMetric(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Metric = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetSystemUsageParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *GetSystemUsageParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/cdr/restapi/operations/usage_management/get_system_usage_responses.go b/services/cdr/restapi/operations/usage_management/get_system_usage_responses.go new file mode 100644 index 0000000..c1cce0b --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_system_usage_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetSystemUsageOKCode is the HTTP code returned for type GetSystemUsageOK +const GetSystemUsageOKCode int = 200 + +/*GetSystemUsageOK Description of a successfully operation + +swagger:response getSystemUsageOK +*/ +type GetSystemUsageOK struct { + + /* + In: Body + */ + Payload []*models.CReport `json:"body,omitempty"` +} + +// NewGetSystemUsageOK creates GetSystemUsageOK with default headers values +func NewGetSystemUsageOK() *GetSystemUsageOK { + + return &GetSystemUsageOK{} +} + +// WithPayload adds the payload to the get system usage o k response +func (o *GetSystemUsageOK) WithPayload(payload []*models.CReport) *GetSystemUsageOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get system usage o k response +func (o *GetSystemUsageOK) SetPayload(payload []*models.CReport) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSystemUsageOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.CReport, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetSystemUsageInternalServerErrorCode is the HTTP code returned for type GetSystemUsageInternalServerError +const GetSystemUsageInternalServerErrorCode int = 500 + +/*GetSystemUsageInternalServerError Something unexpected happend, error raised + +swagger:response getSystemUsageInternalServerError +*/ +type GetSystemUsageInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSystemUsageInternalServerError creates GetSystemUsageInternalServerError with default headers values +func NewGetSystemUsageInternalServerError() *GetSystemUsageInternalServerError { + + return &GetSystemUsageInternalServerError{} +} + +// WithPayload adds the payload to the get system usage internal server error response +func (o *GetSystemUsageInternalServerError) WithPayload(payload *models.ErrorResponse) *GetSystemUsageInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get system usage internal server error response +func (o *GetSystemUsageInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSystemUsageInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/cdr/restapi/operations/usage_management/get_system_usage_urlbuilder.go b/services/cdr/restapi/operations/usage_management/get_system_usage_urlbuilder.go new file mode 100644 index 0000000..40a5857 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_system_usage_urlbuilder.go @@ -0,0 +1,132 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/strfmt" +) + +// GetSystemUsageURL generates an URL for the get system usage operation +type GetSystemUsageURL struct { + From *strfmt.DateTime + Idlist *string + Metric *string + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSystemUsageURL) WithBasePath(bp string) *GetSystemUsageURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSystemUsageURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetSystemUsageURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/usage" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var idlistQ string + if o.Idlist != nil { + idlistQ = *o.Idlist + } + if idlistQ != "" { + qs.Set("idlist", idlistQ) + } + + var metricQ string + if o.Metric != nil { + metricQ = *o.Metric + } + if metricQ != "" { + qs.Set("metric", metricQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetSystemUsageURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetSystemUsageURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetSystemUsageURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetSystemUsageURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetSystemUsageURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetSystemUsageURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage.go b/services/cdr/restapi/operations/usage_management/get_usage.go new file mode 100644 index 0000000..edc7ae4 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetUsageHandlerFunc turns a function with the right signature into a get usage handler +type GetUsageHandlerFunc func(GetUsageParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetUsageHandlerFunc) Handle(params GetUsageParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetUsageHandler interface for that can handle valid get usage params +type GetUsageHandler interface { + Handle(GetUsageParams, interface{}) middleware.Responder +} + +// NewGetUsage creates a new http.Handler for the get usage operation +func NewGetUsage(ctx *middleware.Context, handler GetUsageHandler) *GetUsage { + return &GetUsage{Context: ctx, Handler: handler} +} + +/*GetUsage swagger:route GET /usage/{id} usageManagement getUsage + +Detailed report covering of the account associated with the id within the specified time window + +*/ +type GetUsage struct { + Context *middleware.Context + Handler GetUsageHandler +} + +func (o *GetUsage) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetUsageParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage_parameters.go b/services/cdr/restapi/operations/usage_management/get_usage_parameters.go new file mode 100644 index 0000000..8905a0d --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage_parameters.go @@ -0,0 +1,193 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetUsageParams creates a new GetUsageParams object +// no default values defined in spec. +func NewGetUsageParams() GetUsageParams { + + return GetUsageParams{} +} + +// GetUsageParams contains all the bound params for the get usage operation +// typically these are obtained from a http.Request +// +// swagger:parameters getUsage +type GetUsageParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to get the usage report + In: query + */ + From *strfmt.DateTime + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Metric(s) to get the usage report + In: query + */ + Metric *string + /*Datetime until which to get the usage report + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetUsageParams() beforehand. +func (o *GetUsageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qMetric, qhkMetric, _ := qs.GetOK("metric") + if err := o.bindMetric(qMetric, qhkMetric, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetUsageParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *GetUsageParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetUsageParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMetric binds and validates parameter Metric from query. +func (o *GetUsageParams) bindMetric(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Metric = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetUsageParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *GetUsageParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage_responses.go b/services/cdr/restapi/operations/usage_management/get_usage_responses.go new file mode 100644 index 0000000..3f72e47 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetUsageOKCode is the HTTP code returned for type GetUsageOK +const GetUsageOKCode int = 200 + +/*GetUsageOK Description of a successfully operation + +swagger:response getUsageOK +*/ +type GetUsageOK struct { + + /* + In: Body + */ + Payload []*models.CReport `json:"body,omitempty"` +} + +// NewGetUsageOK creates GetUsageOK with default headers values +func NewGetUsageOK() *GetUsageOK { + + return &GetUsageOK{} +} + +// WithPayload adds the payload to the get usage o k response +func (o *GetUsageOK) WithPayload(payload []*models.CReport) *GetUsageOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage o k response +func (o *GetUsageOK) SetPayload(payload []*models.CReport) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.CReport, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetUsageInternalServerErrorCode is the HTTP code returned for type GetUsageInternalServerError +const GetUsageInternalServerErrorCode int = 500 + +/*GetUsageInternalServerError Something unexpected happend, error raised + +swagger:response getUsageInternalServerError +*/ +type GetUsageInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetUsageInternalServerError creates GetUsageInternalServerError with default headers values +func NewGetUsageInternalServerError() *GetUsageInternalServerError { + + return &GetUsageInternalServerError{} +} + +// WithPayload adds the payload to the get usage internal server error response +func (o *GetUsageInternalServerError) WithPayload(payload *models.ErrorResponse) *GetUsageInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage internal server error response +func (o *GetUsageInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage_summary.go b/services/cdr/restapi/operations/usage_management/get_usage_summary.go new file mode 100644 index 0000000..373269d --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage_summary.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetUsageSummaryHandlerFunc turns a function with the right signature into a get usage summary handler +type GetUsageSummaryHandlerFunc func(GetUsageSummaryParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetUsageSummaryHandlerFunc) Handle(params GetUsageSummaryParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetUsageSummaryHandler interface for that can handle valid get usage summary params +type GetUsageSummaryHandler interface { + Handle(GetUsageSummaryParams, interface{}) middleware.Responder +} + +// NewGetUsageSummary creates a new http.Handler for the get usage summary operation +func NewGetUsageSummary(ctx *middleware.Context, handler GetUsageSummaryHandler) *GetUsageSummary { + return &GetUsageSummary{Context: ctx, Handler: handler} +} + +/*GetUsageSummary swagger:route GET /usage/summary/{id} usageManagement getUsageSummary + +Summary report meant for the UI for the resources linked to the ResellerID provided within the specified time window + +*/ +type GetUsageSummary struct { + Context *middleware.Context + Handler GetUsageSummaryHandler +} + +func (o *GetUsageSummary) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetUsageSummaryParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage_summary_parameters.go b/services/cdr/restapi/operations/usage_management/get_usage_summary_parameters.go new file mode 100644 index 0000000..77db437 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage_summary_parameters.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetUsageSummaryParams creates a new GetUsageSummaryParams object +// no default values defined in spec. +func NewGetUsageSummaryParams() GetUsageSummaryParams { + + return GetUsageSummaryParams{} +} + +// GetUsageSummaryParams contains all the bound params for the get usage summary operation +// typically these are obtained from a http.Request +// +// swagger:parameters getUsageSummary +type GetUsageSummaryParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to get the usage report + In: query + */ + From *strfmt.DateTime + /*Id of the reseller to be checked + Required: true + In: path + */ + ID string + /*Datetime until which to get the usage report + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetUsageSummaryParams() beforehand. +func (o *GetUsageSummaryParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetUsageSummaryParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *GetUsageSummaryParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetUsageSummaryParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetUsageSummaryParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *GetUsageSummaryParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage_summary_responses.go b/services/cdr/restapi/operations/usage_management/get_usage_summary_responses.go new file mode 100644 index 0000000..0975672 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage_summary_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" +) + +// GetUsageSummaryOKCode is the HTTP code returned for type GetUsageSummaryOK +const GetUsageSummaryOKCode int = 200 + +/*GetUsageSummaryOK Description of a successfully operation + +swagger:response getUsageSummaryOK +*/ +type GetUsageSummaryOK struct { + + /* + In: Body + */ + Payload *models.UISummary `json:"body,omitempty"` +} + +// NewGetUsageSummaryOK creates GetUsageSummaryOK with default headers values +func NewGetUsageSummaryOK() *GetUsageSummaryOK { + + return &GetUsageSummaryOK{} +} + +// WithPayload adds the payload to the get usage summary o k response +func (o *GetUsageSummaryOK) WithPayload(payload *models.UISummary) *GetUsageSummaryOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage summary o k response +func (o *GetUsageSummaryOK) SetPayload(payload *models.UISummary) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageSummaryOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetUsageSummaryInternalServerErrorCode is the HTTP code returned for type GetUsageSummaryInternalServerError +const GetUsageSummaryInternalServerErrorCode int = 500 + +/*GetUsageSummaryInternalServerError Something unexpected happend, error raised + +swagger:response getUsageSummaryInternalServerError +*/ +type GetUsageSummaryInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetUsageSummaryInternalServerError creates GetUsageSummaryInternalServerError with default headers values +func NewGetUsageSummaryInternalServerError() *GetUsageSummaryInternalServerError { + + return &GetUsageSummaryInternalServerError{} +} + +// WithPayload adds the payload to the get usage summary internal server error response +func (o *GetUsageSummaryInternalServerError) WithPayload(payload *models.ErrorResponse) *GetUsageSummaryInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage summary internal server error response +func (o *GetUsageSummaryInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageSummaryInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage_summary_urlbuilder.go b/services/cdr/restapi/operations/usage_management/get_usage_summary_urlbuilder.go new file mode 100644 index 0000000..dc57617 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage_summary_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// GetUsageSummaryURL generates an URL for the get usage summary operation +type GetUsageSummaryURL struct { + ID string + + From *strfmt.DateTime + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageSummaryURL) WithBasePath(bp string) *GetUsageSummaryURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageSummaryURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetUsageSummaryURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/usage/summary/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetUsageSummaryURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetUsageSummaryURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetUsageSummaryURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetUsageSummaryURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetUsageSummaryURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetUsageSummaryURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetUsageSummaryURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/cdr/restapi/operations/usage_management/get_usage_urlbuilder.go b/services/cdr/restapi/operations/usage_management/get_usage_urlbuilder.go new file mode 100644 index 0000000..7ca9a83 --- /dev/null +++ b/services/cdr/restapi/operations/usage_management/get_usage_urlbuilder.go @@ -0,0 +1,133 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// GetUsageURL generates an URL for the get usage operation +type GetUsageURL struct { + ID string + + From *strfmt.DateTime + Metric *string + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageURL) WithBasePath(bp string) *GetUsageURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetUsageURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/usage/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetUsageURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var metricQ string + if o.Metric != nil { + metricQ = *o.Metric + } + if metricQ != "" { + qs.Set("metric", metricQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetUsageURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetUsageURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetUsageURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetUsageURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetUsageURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetUsageURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/cdr/restapi/server.go b/services/cdr/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/services/cdr/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/services/cdr/run/cert.crt b/services/cdr/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/cdr/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/cdr/run/config.toml b/services/cdr/run/config.toml new file mode 100644 index 0000000..61e5b28 --- /dev/null +++ b/services/cdr/run/config.toml @@ -0,0 +1,89 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "23h" +DBName = "cyclops" +Host = "localhost" +Password = "pass1234" +Port = 5432 +# SSLMode = enable | disable +SSLMode = "disable" +UserName = "cyclops" + +[EVENTS] +Filters = [ "filter1", "filter2" ] + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +# "" for no file-logging +LogFile = "" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8000" +CDR = "cdr:8000" +CreditManager = "creditsystem:8000" +CustomerDB = "customerdb:8000" +EventsEngine = "eventsengine:8000" +PlanManager = "planmanager:8000" +UDR = "udr:8000" + +[KAFKA] +Brokers = [ "kafka1:9092", "kafka2:9092", "kafka3:9092" ] +CDRIn = [ "CDR" ] +CDROut = [ "Credit" ] +Credit-SystemIn = [ "Credit" ] +EventsEngineIn = [ "Events" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMin = 10e3 +SizeMax = 10e6 +UDRIn = [ "UDR" ] +UDROut = [ "CDR" ] + +[PLANS] +Default = "-1" +Education = "-2" + +[PROMETHEUS] +Host = "prometheus:9090" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + diff --git a/services/cdr/run/docker-compose.yml b/services/cdr/run/docker-compose.yml new file mode 100644 index 0000000..8a6e52e --- /dev/null +++ b/services/cdr/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: SERVICE:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/services/cdr/run/key.key b/services/cdr/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/cdr/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/cdr/server/cache.go b/services/cdr/server/cache.go new file mode 100644 index 0000000..bc18342 --- /dev/null +++ b/services/cdr/server/cache.go @@ -0,0 +1,553 @@ +package main + +import ( + "context" + "net/url" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + cdrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client" + cdrUsage "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/usage_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/cacheManager" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + cusCustomer "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/customer_management" + cusProduct "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/product_management" + cusReseller "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/reseller_management" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + pmBundle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/bundle_management" + pmCycle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/cycle_management" + pmPlan "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/plan_management" + pmSku "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/sku_management" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheStart handles the initialization of the cache mechanism service. +// Returns: +// - A cacheManager reference struct already initialized and ready to be used. +func cacheStart(metrics *prometheus.GaugeVec) *cacheManager.CacheManager { + + l.Trace.Printf("[CACHE][INIT] Intializing cache mechanism.\n") + + cacheDuration, _ := time.ParseDuration(cfg.DB.CacheRetention) + + c := cacheManager.New(metrics, cacheDuration, cfg.APIKey.Token) + + resellerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusReseller.NewGetResellerParams().WithID(i) + + r, e := client.ResellerManagement.GetReseller(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the reseller with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusReseller.NewListResellersParams() + + r, e := client.ResellerManagement.ListResellers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of resellers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + customerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusCustomer.NewGetCustomerParams().WithID(i) + + r, e := client.CustomerManagement.GetCustomer(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the customer with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusCustomer.NewListCustomersParams() + + r, e := client.CustomerManagement.ListCustomers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of customers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + productFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusProduct.NewGetProductParams().WithID(i) + + r, e := client.ProductManagement.GetProduct(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the product with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusProduct.NewListProductsParams() + + r, e := client.ProductManagement.ListProducts(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of products. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + // id == id0[,id1,...,idN]?from?to + cdrFunction := func(id interface{}, token string) (interface{}, error) { + + config := cdrClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["cdr"], + Path: cdrClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + idSplit := strings.SplitN(id.(string), "?", 3) + + i := idSplit[0] + + from, e := time.Parse(time.RFC3339Nano, idSplit[1]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[1], e) + + return nil, e + + } + + f := (strfmt.DateTime)(from) + + to, e := time.Parse(time.RFC3339Nano, idSplit[2]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[2], e) + + return nil, e + + } + + t := (strfmt.DateTime)(to) + + client := cdrClient.New(config) + ctx := context.Background() + + if strings.Contains(i, ",") { + + params := cdrUsage.NewGetSystemUsageParams().WithIdlist(&i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + if i != "ALL" { + + params := cdrUsage.NewGetUsageParams().WithID(i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving the CDRs under the id [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := cdrUsage.NewGetSystemUsageParams().WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + skuFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmSku.NewGetSkuParams().WithID(id.(string)) + + r, e := client.SkuManagement.GetSku(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the sku [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := pmSku.NewListSkusParams() + + r, e := client.SkuManagement.ListSkus(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the skus list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + planFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + var planID string + + if i, exists := cfg.DefaultPlans[strings.ToLower(id.(string))]; exists { + + planID = i + + } else { + + planID = id.(string) + + } + + params := pmPlan.NewGetCompletePlanParams().WithID(planID) + + r, e := client.PlanManagement.GetCompletePlan(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmPlan.NewListCompletePlansParams() + + r, e := client.PlanManagement.ListCompletePlans(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + bundleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmBundle.NewGetSkuBundleParams().WithID(id.(string)) + + r, e := client.BundleManagement.GetSkuBundle(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmBundle.NewListSkuBundlesParams() + + r, e := client.BundleManagement.ListSkuBundles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + cycleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + var params *pmCycle.ListCyclesParams + + if id.(string) == "ALL" { + + params = pmCycle.NewListCyclesParams() + + } else { + + ty := id.(string) + + params = pmCycle.NewListCyclesParams().WithType(&ty) + + } + + r, e := client.CycleManagement.ListCycles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CYCLE-FUNCTION] There was a problem while retrieving the cycle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + c.Add("reseller", resellerFunction) + l.Trace.Printf("[CACHE][INIT] Reseller fetcher added to the cache.\n") + + c.Add("customer", customerFunction) + l.Trace.Printf("[CACHE][INIT] Customer fetcher added to the cache.\n") + + c.Add("product", productFunction) + l.Trace.Printf("[CACHE][INIT] Product fetcher added to the cache.\n") + + c.Add("cdr", cdrFunction) + l.Trace.Printf("[CACHE][INIT] CDR usage fetcher added to the cache.\n") + + c.Add("sku", skuFunction) + l.Trace.Printf("[CACHE][INIT] SKU fetcher added to the cache.\n") + + c.Add("plan", planFunction) + l.Trace.Printf("[CACHE][INIT] Plan fetcher added to the cache.\n") + + c.Add("bundle", bundleFunction) + l.Trace.Printf("[CACHE][INIT] SkuBundle fetcher added to the cache.\n") + + c.Add("cycle", cycleFunction) + l.Trace.Printf("[CACHE][INIT] Life Cycle fetcher added to the cache.\n") + + return c + +} diff --git a/services/cdr/server/cacheManager/cacheManager.go b/services/cdr/server/cacheManager/cacheManager.go new file mode 100644 index 0000000..9da44a3 --- /dev/null +++ b/services/cdr/server/cacheManager/cacheManager.go @@ -0,0 +1,277 @@ +package cacheManager + +import ( + "fmt" + "strings" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheFetchFunction it will need the id to retrieve and as and option a Bearer +// Keycloak token can be provided when called. +// It shall return the object and errors in case of problems. +type cacheFetchFunction func(interface{}, string) (interface{}, error) + +// cache struct is the main "object" which handles the cache and its items. +// It also contains a map with the conversions of interfaces to strings. +type cache struct { + ////conversionDictionary map[string]string + data map[string]*cacheItem + fetchers map[string]cacheFetchFunction + mutex sync.RWMutex +} + +// cacheItem struct referes to the data of each element saved in the cache. +type cacheItem struct { + fetcher cacheFetchFunction + lastUpdate time.Time + value interface{} +} + +// CacheManager is the struct defined to group and contain all the methods +// that interact with the caching mechanism. +type CacheManager struct { + APIKey string + duration time.Duration + metrics *prometheus.GaugeVec + store cache +} + +// New is the function to create the struct CacheManager. +// Parameters: +// - t: a time.Duration with the max duration alive of the cache elements. +// - k: string containing the APIKey/token in case of need. +// Returns: +// - CacheManager: struct to interact with CacheManager subsystem functionalities. +func New(metrics *prometheus.GaugeVec, t time.Duration, k string) *CacheManager { + + l.Trace.Printf("[CACHE] Initializing the cache service.\n") + + c := CacheManager{ + APIKey: k, + duration: t, + metrics: metrics, + store: cache{ + data: make(map[string]*cacheItem), + fetchers: make(map[string]cacheFetchFunction), + }, + } + + return &c + +} + +// Add function job is to insert a new model in the cache. +// What it does is link the model with a fetching function and, if wanted, with +// a plain text name, so later in order to retrieve things from the cache they +// can be refereced either by the struct model or the plain text name. +// Paramenters: +// - plainName: a case insensitive name/alias to retrieve the data. +// - fetcher: the cacheFetchFunction used to retrieve the data. +func (c *CacheManager) Add(plainName string, fetcher cacheFetchFunction) { + + l.Trace.Printf("[CACHE] Adding a new object fetcher in the cache.\n") + + key := strings.ToUpper(plainName) + + c.store.mutex.Lock() + + c.store.fetchers[key] = fetcher + + c.store.mutex.Unlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Models in Cache"}).Inc() + + return + +} + +// fetch function job is to retrieve a new and updated copy of the remote object. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) fetch(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + c.store.mutex.RLock() + + object := c.store.data[item] + + c.store.mutex.RUnlock() + + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := object.fetcher(id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + object.value = uValue + object.lastUpdate = time.Now() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// fetch function job is to create the new item in the cache and retrieve a new +// and updated initial copy of the remote object to be saved in the cache. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) init(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + key := strings.Split(item, "-")[0] + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := c.store.fetchers[key](id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + i := cacheItem{ + fetcher: c.store.fetchers[key], + lastUpdate: time.Now(), + value: uValue, + } + + c.store.mutex.Lock() + + c.store.data[item] = &i + + c.store.mutex.Unlock() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// key is a function to ensure that the creation of the the item key for the +// cache is consistent across all the functions. +// Paramenters: +// - id: the reference id of the object to be retrieved +// - model: the alias text used to identify the source of objects. +// Returns: +// - s: the key string +func (c *CacheManager) key(id interface{}, model string) (s string) { + + s = fmt.Sprintf("%v-%v", strings.ToUpper(model), id) + + return + +} + +// Get function job is to retrieve an object from the cache or fetch it from the +// source and upgrade the copy in the cache in case the expiration time has been +// exceeded. +// Paramenters: +// - id: the reference id of the object. +// - model: the text alias set to reference the model. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - The object associated with the request +// - An error raised in case something went wrong while retrieving the object. +func (c *CacheManager) Get(id interface{}, model string, token string) (interface{}, error) { + + l.Trace.Printf("[CACHE] Retrieving object [ %v, %v ] from the cache.\n", id, model) + + item := c.key(id, model) + + object, exists := c.store.data[item] + + if !exists { + + l.Trace.Printf("[CACHE] Object [ %v ] first time requested, including in the cache.\n", item) + + if e := c.init(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while adding the new item [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects cached"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects cached"}).Inc() + + return o, nil + + } + + l.Trace.Printf("[CACHE] Object [ %v ] exists in the cache.\n", item) + + c.store.mutex.Lock() + + diff := (time.Now()).Sub(c.store.data[item].lastUpdate) + + c.store.mutex.Unlock() + + if diff <= c.duration { + + l.Trace.Printf("[CACHE] Object [ %v ] cache hasn't expired yet.\n", item) + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return object.value, nil + + } + + l.Warning.Printf("[CACHE] Object [ %v ] cache has expired. Starting the upgrade.\n", item) + + if e := c.fetch(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while fetching the updated data for the object [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects refreshed"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] updated retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects refreshed"}).Inc() + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return o, nil + +} diff --git a/services/cdr/server/config.go b/services/cdr/server/config.go new file mode 100644 index 0000000..4eb0cf9 --- /dev/null +++ b/services/cdr/server/config.go @@ -0,0 +1,223 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + DefaultPlans map[string]string + Prometheus prometheusConfig +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type planConfig struct { + Default string +} +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("database.cacheretention"), + DbName: viper.GetString("database.dbname"), + Host: viper.GetString("database.host"), + Password: viper.GetString("database.password"), + Port: viper.GetInt("database.port"), + SSLMode: viper.GetString("database.sslmode"), + Username: viper.GetString("database.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + DefaultPlans: viper.GetStringMapString("plans"), + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/services/cdr/server/dbManager/dbManager.go b/services/cdr/server/dbManager/dbManager.go new file mode 100644 index 0000000..85708bf --- /dev/null +++ b/services/cdr/server/dbManager/dbManager.go @@ -0,0 +1,1086 @@ +package dbManager + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "reflect" + "strconv" + "strings" + "time" + + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + datamodels "gitlab.com/cyclops-utilities/datamodels" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/cacheManager" + cusModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + pmModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +const ( + scaler = 1e9 + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +var ( + totalTime float64 + totalCount int64 +) + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// On it there is the following parameters: +// - Cache: CacheManager pointer for the cache mechanism. +// - connStr: strings with the connection information to the database. +// - Db: a gorm.DB pointer to the db to invoke all the db methods. +type DbParameter struct { + Cache *cacheManager.CacheManager + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec + Pipe chan interface{} +} + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database. +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization. +// Returns: +// - DbParameter: struct to interact with dbManager functionalities. +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + } + + l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + dp.Db.AutoMigrate(tables...) + + //l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + //dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NewScope(&models.TABLE).TableName() + "', 'TIMESCALE-ROW-INDEX');") + + return &dp + +} + +// AddRecord job is to save in the system the provided CDR report to be easy to +// retrieve later with the usage endpoints. +// Parameters: +// - cdr: the CDR report model to be added to the system. +// Returns: +// - e: error in case of duplication or failure in the task. +func (d *DbParameter) AddRecord(cdr models.CReport) (e error) { + + l.Trace.Printf("[DB] Attempting to add a new cost report to the system.\n") + + if r := d.Db.Where(&cdr).First(&models.CReport{}).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + e = d.Db.Create(&cdr).Error + + if e != nil { + + l.Trace.Printf("[DB] Something went wrong when adding a new usage report to the system. Error: %v\n", e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "CDR Reports added"}).Inc() + + l.Trace.Printf("[DB] New cost report added to the system.\n") + + } + + } else { + + l.Warning.Printf("[DB] Cost report already in the system, skipping creation...\n") + + } + + l.Trace.Printf("[DB] Attempting to add CDR Records from reported account [ %v ] to the system.\n", cdr.AccountID) + + for i := range cdr.Usage { + + var cdrrecord, cdrUpdate models.CDRRecord + + cdrrecord.AccountID = cdr.AccountID + cdrrecord.Metadata = cdr.Usage[i].Metadata + cdrrecord.ResourceID = cdr.Usage[i].ResourceID + cdrrecord.ResourceName = cdr.Usage[i].ResourceName + cdrrecord.ResourceType = cdr.Usage[i].ResourceType + cdrrecord.TimeFrom = cdr.TimeFrom + cdrrecord.TimeTo = cdr.TimeTo + cdrrecord.Unit = cdr.Usage[i].Unit + + if r := d.Db.Where(&cdrrecord).First(&cdrUpdate).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + cdrrecord.Cost = cdr.Usage[i].Cost + cdrrecord.UsageBreakup = cdr.Usage[i].UsageBreakup + + if e = d.Db.Create(&cdrrecord).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong when adding a new CDR Record to the system. Error: %v\n", e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "CDR Records added"}).Inc() + + l.Trace.Printf("[DB] New CDR Record added in the system.\n") + + } + + } else { + + l.Trace.Printf("[DB] CDR record already in the system, updating...\n") + + cdrrecord.Cost = cdr.Usage[i].Cost + cdrrecord.UsageBreakup = cdr.Usage[i].UsageBreakup + + if e = d.Db.Model(&cdrUpdate).Updates(&cdrrecord).Error; e == nil { + + d.Metrics["count"].With(prometheus.Labels{"type": "CDR Records updated"}).Inc() + + l.Trace.Printf("[DB] CDR Record updated in the system.\n") + + } else { + + l.Trace.Printf("[DB] Something went wrong when updating the existing CDR Record to the system. Error: %v\n", e) + + } + + } + + } + + return + +} + +// GetReport job is to retrieve the compacted usage records from the system for +// the provided account in the requested time-window with the posibility of +// filter by metric. +// Parameters: +// - id: string containing the id of the account requested. +// - metric: a string with the metric to filter the records. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a slice of references with the usage contained in the system within the +// requested time-window. +func (d *DbParameter) GetReport(id string, metric string, from strfmt.DateTime, to strfmt.DateTime) []*models.CDRReport { + + l.Trace.Printf("[DB] Attempting to retrieve the compacted usage records.\n") + + var r []*models.CDRReport + var u models.CDRRecord + + window := d.getWindow(from, to) + + if id != "" { + + u.AccountID = id + + } + + if metric != "" { + + u.ResourceType = metric + + } + + if e := d.Db.Where(window).Where(&u).Find(&models.CDRRecord{}).Scan(&r).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the compacted usage records from the system. Error: %v\n", e) + + } else { + + l.Debug.Printf("[DB] [ %v ] compacted usage records retrieved from the system.\n", len(r)) + + } + + return r + +} + +// GetUsage job is to retrieve the usage report of the system or the specified +// account within the requested time-window with the posibility to filter by +// metric. +// Parameters: +// - id: string containing the id of the account requested. +// - metric: a string with the metric to filter the records. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a slice of references with the usage report contained in the system within +// the requested time-window. +// - error in case of duplication or failure in the task. +func (d *DbParameter) GetUsage(id, metric string, from, to strfmt.DateTime) ([]*models.CReport, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the usage report from the system.\n") + + var r []*models.CReport + var r0 models.CReport + var e error + + window := d.getWindow(from, to) + + if id != "" { + + r0.AccountID = id + + } + + e = d.Db.Where(window).Where(&r0).Find(&r).Error + + if e == nil { + + for idx := range r { + + r[idx].Usage = d.GetReport(r[idx].AccountID, metric, r[idx].TimeFrom, r[idx].TimeTo) + + } + + l.Debug.Printf("[DB] [ %v ] Usage reports retrieved from the system.\n", len(r)) + + } else { + + l.Warning.Printf("[DB] Something went wrong while retrieving the usage reports from the system. Error: %v\n", e) + + } + + return r, e + +} + +// GetUsages job is to retrieve the usage report of the system or the specified +// account accounts within the requested time-window with the posibility to +// filter by metric. +// Parameters: +// - ids: string containing the list of ids of the accounts requested. +// - metric: a string with the metric to filter the records. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a slice of references with the usage report contained in the system within +// the requested time-window. +// - error in case of duplication or failure in the task. +func (d *DbParameter) GetUsages(ids, metric string, from, to strfmt.DateTime) ([]*models.CReport, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the usage report from the system.\n") + + var total, r []*models.CReport + var r0 models.CReport + var e error + + window := d.getWindow(from, to) + + list := strings.Split(ids, ",") + + for _, acc := range list { + + r0.AccountID = acc + + if e = d.Db.Where(window).Where(&r0).Find(&r).Error; e == nil { + + for idx := range r { + + r[idx].Usage = d.GetReport(r[idx].AccountID, metric, r[idx].TimeFrom, r[idx].TimeTo) + + } + + l.Debug.Printf("[DB] [ %v ] Usage reports retrieved from the system.\n", len(r)) + + } else { + + l.Warning.Printf("[DB] Something went wrong while retrieving the usage reports from the system. Error: %v\n", e) + + } + + total = append(total, r...) + + } + + return total, e + +} + +// GetUsageSummary job is to retrieve the usage report of the system of the specified +// account within the requested time-window and process it into an easy to use +// estructure for the UI. +// Parameters: +// - id: string containing the id of the account requested. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a references with the usage report contained in the system within +// the requested time-window. +// - error in case of duplication or failure in the task. +func (d *DbParameter) GetUsageSummary(id string, from, to strfmt.DateTime) (*models.UISummary, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the usage report from the system.\n") + + var usages []*models.CDRReport + var report models.UISummary + + interval := float64(28800) //UDR are created every 8h and the usage is provided in GB*s... + rounder := float64(((time.Time)(to)).Sub((time.Time)(from)).Seconds()) / interval + + report.AccountID = id + report.TimeFrom = from + report.TimeTo = to + + // Get the reseller data + r, err := d.Cache.Get(id, "reseller", "") + + if err != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the reseller info for id [ %v ]. Error: %v\n", id, err) + + return nil, err + + } + + reseller := r.(cusModels.Reseller) + + // Get all the usages linked to the reseller + for _, customer := range reseller.Customers { + + for _, product := range customer.Products { + + u := d.GetReport(product.ProductID, "", from, to) + + usages = append(usages, u...) + + } + + } + + // Scan the usages and make the numbers + resourcesMap := make(datamodels.JSONdb) + + for i := range usages { + + masterKey := strings.ToTitle(usages[i].ResourceType) + + if _, exists := resourcesMap[masterKey]; !exists { + + resourcesMap[masterKey] = make(datamodels.JSONdb) + + } + + // First the total + key := "TotalCount" + if _, exists := resourcesMap[masterKey].(datamodels.JSONdb)[key]; !exists { + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = float64(0) + + } + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = resourcesMap[masterKey].(datamodels.JSONdb)[key].(float64) + float64(1/rounder) + + // Second the regions + if region, exists := usages[i].Metadata["region"]; exists { + + key := "Regions" + + if _, exists := resourcesMap[masterKey].(datamodels.JSONdb)[key]; !exists { + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = make(datamodels.JSONdb) + + } + + regionKey := region.(string) + if _, exists := resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[regionKey]; !exists { + + resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[regionKey] = float64(0) + + } + + resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[regionKey] = resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[regionKey].(float64) + float64(1/rounder) + + } + + // Third the flavors in case of + if flavor, exists := usages[i].Metadata["flavorname"]; exists { + + key := "Flavors" + + if _, exists := resourcesMap[masterKey].(datamodels.JSONdb)[key]; !exists { + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = make(datamodels.JSONdb) + + } + + flavorKey := flavor.(string) + if _, exists := resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[flavorKey]; !exists { + + resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[flavorKey] = float64(0) + + } + + resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[flavorKey] = resourcesMap[masterKey].(datamodels.JSONdb)[key].(datamodels.JSONdb)[flavorKey].(float64) + float64(1/rounder) + + } + + // Fourth the sizes in case of + if size, exists := usages[i].Metadata["size"]; exists { + + sizeF, err := strconv.ParseFloat(size.(string), 64) + + if err != nil { + + l.Warning.Printf("[DB] Failed to turn the size [ %v ] into a float64 value. Error: %v\n", size, err) + + } else { + + key := "TotalAmount" + + if _, exists := resourcesMap[key]; !exists { + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = float64(0) + + } + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = resourcesMap[masterKey].(datamodels.JSONdb)[key].(float64) + float64(sizeF/rounder) + + } + + } + + // UDR usages + if size, exists := usages[i].UsageBreakup["used"]; exists { + + var sizeF float64 + key := "TotalAmount" + + // size to float64 + if k := reflect.ValueOf(size); k.Kind() == reflect.Float64 { + + sizeF = size.(float64) / interval + + } else { + + v, err := size.(json.Number).Float64() + + if err != nil { + + l.Warning.Printf("[DB] Failed to turn the size [ %v ] into a float64 value. Error: %v\n", size, err) + + } else { + + sizeF = float64(v) / interval + + } + + } + + if _, exists := resourcesMap[masterKey].(datamodels.JSONdb)[key]; !exists { + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = float64(0) + + } + + resourcesMap[masterKey].(datamodels.JSONdb)[key] = resourcesMap[masterKey].(datamodels.JSONdb)[key].(float64) + float64(sizeF/rounder) + + } + + } + + // Reshape of the JSON to easy showing in the front.. + for key, value := range resourcesMap { + + metricData := value.(datamodels.JSONdb) + + if _, exists := metricData["Regions"]; exists { + + var regions []datamodels.JSONdb + + for k, v := range metricData["Regions"].(datamodels.JSONdb) { + + region := make(datamodels.JSONdb) + region["name"] = k + region["amount"] = v + + regions = append(regions, region) + + } + + resourcesMap[key].(datamodels.JSONdb)["Regions"] = regions + + } + + if _, exists := metricData["Flavors"]; exists { + + var regions []datamodels.JSONdb + + for k, v := range metricData["Flavors"].(datamodels.JSONdb) { + + region := make(datamodels.JSONdb) + region["name"] = k + region["amount"] = v + + regions = append(regions, region) + + } + + resourcesMap[key].(datamodels.JSONdb)["Flavors"] = regions + + } + + } + + // Create the summarey report + report.UsageBreakup = resourcesMap + + return &report, nil + +} + +// getWindow job is to select the timeframe for the usage retrievals according +// to the data providad from= '%v'", d.Db.NamingStrategy.ColumnName("", "TimeFrom"), from) + + } else { + + s = fmt.Sprintf("%v >= '%v' AND %v <= '%v'", d.Db.NamingStrategy.ColumnName("", "TimeFrom"), from, d.Db.NamingStrategy.ColumnName("", "TimeTo"), to) + + } + + } else { + + if !((time.Time)(to)).IsZero() { + + s = fmt.Sprintf("%v <= '%v'", d.Db.NamingStrategy.ColumnName("", "TimeTo"), to) + + } + + } + + return s + +} + +// ProcessUDR job is to process the UDR Reports and turn then into CDR Reports +// and store them in the system. +// Parameters: +// - report: UDR Report model reference to be processed. +// - token: an optional keycloak token in case it's provided. +// Returns: +// - e: error in case of duplication or failure in the task. +func (d *DbParameter) ProcessUDR(report udrModels.UReport, token string) (e error) { + + l.Trace.Printf("[DB] Attempting to process and transform the UDR report into a CDR report and save it to the system.\n") + + // First we clean all the records so we always have a clean UDR generation + templateRecord := models.CDRRecord{ + AccountID: report.AccountID, + TimeFrom: report.TimeFrom, + TimeTo: report.TimeTo, + } + + l.Info.Printf("[DB] Clean up of previous CDRRecords started for period [ %v ] - [ %v ].\n", report.TimeFrom, report.TimeTo) + + if e := d.Db.Where(&templateRecord).Delete(&models.CDRRecord{}).Error; e != nil { + + l.Warning.Printf("[DB] The clean up of previous CDRecords failed. Error: %v\n", e) + + } + + templateReport := models.CReport{ + AccountID: report.AccountID, + TimeFrom: report.TimeFrom, + TimeTo: report.TimeTo, + } + + l.Info.Printf("[DB] Clean up of previous CReports started for period [ %v ] - [ %v ].\n", report.TimeFrom, report.TimeTo) + + if e := d.Db.Where(&templateReport).Delete(&models.CReport{}).Error; e != nil { + + l.Warning.Printf("[DB] The clean up of previous CReports failed. Error: %v\n", e) + + } + + // First we get the metric and accounts in the system. + var planID string + var cdr models.CReport + var usages []*models.CDRReport + + now := time.Now().UnixNano() + + x, e := d.Cache.Get(report.AccountID, "product", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the product info for id [ %v ]. Error: %v\n", report.AccountID, e) + + return + + } + + product := x.(cusModels.Product) + + if product.PlanID != "" { + + planID = product.PlanID + + } else if product.Type != "" { + + planID = product.Type + + } else { + + c, e := d.Cache.Get(product.CustomerID, "customer", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the customer info for id [ %v ]. Error: %v\n", product.CustomerID, e) + + return e + + } + + customer := c.(cusModels.Customer) + + if customer.PlanID != "" { + + planID = customer.PlanID + + } else { + + r, e := d.Cache.Get(customer.ResellerID, "reseller", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the reseller info for id [ %v ]. Error: %v\n", customer.ResellerID, e) + + return e + + } + + reseller := r.(cusModels.Reseller) + + planID = reseller.PlanID + + } + + } + +PlanDefault: + p, e := d.Cache.Get(planID, "plan", token) + + if e != nil { + + if planID == "DEFAULT" { + + l.Warning.Printf("[DB] Something went wrong while retrieving the default plan id [ %v ]. Error: %v\n", planID, e) + + return + + } + + l.Warning.Printf("[DB] Something went wrong while retrieving the plan id [ %v ]. Re-trying with default plan. Error: %v\n", planID, e) + + planID = "DEFAULT" + + goto PlanDefault + + } + + plan := p.(pmModels.Plan) + savedPlan := p.(pmModels.Plan) + + // In case the plan is not valid we return to the deault plan (id 0) which is valid ad vitam + if (time.Now()).After((time.Time)(*plan.OfferedEndDate)) || (time.Now()).Before((time.Time)(*plan.OfferedStartDate)) { + + l.Warning.Printf("[DB] The plan [ %v ] is only valid between [ %v ] and [ %v ]. Falling back to default plan.\n", plan.ID, *plan.OfferedStartDate, *plan.OfferedEndDate) + + planID = "DEFAULT" + + goto PlanDefault + + } + + s, e := d.Cache.Get("ALL", "sku", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the skus list. Error: %v\n", e) + + return + + } + + skus := make(map[string]string) + + for _, k := range s.([]*pmModels.Sku) { + + skus[*k.Name] = k.ID + + } + + // having the customer and the plan... + // iter the report + for _, u := range report.Usage { + + costBreakup := make(datamodels.JSONdb) + + var costSkuTotal []datamodels.JSONdb + var cycles []*pmModels.Cycle + var bundle pmModels.SkuBundle + var skuDiscount, skuPrice, usage, multiplier, amount, quantity float64 + + // get cycle of resourceType + c, e := d.Cache.Get(u.ResourceType, "cycle", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the states for the life cycle linked to the ResourceType [ %v ]. Error: %v\n", u.ResourceType, e) + + return e + + } + + cycles = c.([]*pmModels.Cycle) + + // if server, get the skubundle associated + if _, exist := cycles[0].SkuList[u.ResourceType]; !exist { + + if id, exists := u.Metadata["flavorid"]; exists { + + b, e := d.Cache.Get(id, "bundle", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the skuBundle id [ %v ]. Error: %v\n", u.Metadata["flavorid"], e) + + return e + + } + + bundle = b.(pmModels.SkuBundle) + + // Usecase: flavor is a generic one but then the image is a windows base one, so the license is not included by default + if id, exists := u.Metadata["imagename"]; exists && strings.Contains(strings.ToLower(id.(string)), "windows") { + + _, license := bundle.SkuPrices["license"] + vcpu, exists := bundle.SkuPrices["vcpu"] + + if !license && exists { + + var previous pmModels.SkuBundle + + previous.ID = bundle.ID + previous.Name = bundle.Name + previous.SkuPrices = make(datamodels.JSONdb) + + for k, v := range bundle.SkuPrices { + + previous.SkuPrices[k] = v + + } + + previous.SkuPrices["license"] = vcpu + + bundle = previous + + } + + } + + } else { + + l.Warning.Printf("[DB] Something is wrong. Error: The flavorid is supposed to exist in the metadata.\n") + + continue + + } + + } + + // METADA OVERRIDERS + if override, exists := u.Metadata["PlanOverride"]; exists && override.(bool) { + + overridePlan, e := d.Cache.Get("DEFAULT", "plan", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the Overriding plan. Error: %v\n", e) + + } else { + + plan = overridePlan.(pmModels.Plan) + + } + + } else { + + plan = savedPlan + + } + + // loop cycle + for i := range cycles { + + // if usageBreakup(cycle.state) !exists, continue + if stateUse, exists := u.UsageBreakup[*(cycles[i].State)]; !exists { + + continue + + // else, get the usage value + } else { + + // usage to float64 + if k := reflect.ValueOf(stateUse); k.Kind() == reflect.Float64 { + + usage = stateUse.(float64) + + } else { + + v, _ := stateUse.(json.Number).Int64() + usage = float64(v) + + } + + } + + // and loop actual.cycle.skus + for sku, value := range cycles[i].SkuList { + + // get the skuDiscount and skuPrice associated + if id, exists := skus[sku]; exists { + + for j := range plan.SkuPrices { + + if *plan.SkuPrices[j].SkuID == id { + + skuDiscount = float64(plan.SkuPrices[j].Discount) + skuPrice = float64(*plan.SkuPrices[j].UnitPrice) + + break + + } + + } + + } else { + + l.Warning.Printf("[DB] Something is wrong. Error: [ %v ] is supposed to exist in the system as a sku.\n", u.ResourceType) + + continue + + } + + // multiplier to float64 + if k := reflect.ValueOf(value); k.Kind() == reflect.Float64 { + + multiplier = value.(float64) + + } else { + + v, _ := value.(json.Number).Int64() + multiplier = float64(v) + + } + + // if resType not server then use actual.cycle.skus as multiplier for usage + if *cycles[i].ResourceType == sku { + + // Size of buckets to be computed + if sz, exists := u.Metadata["size"]; exists { + + size, e := strconv.ParseInt(sz.(string), 10, 0) + + if e != nil { + + l.Warning.Printf("[DB] Something is wrong with the size [ %v ] of the metadata. Error: %v.\n", sz, u.ResourceType) + + amount = usage * multiplier + + } else { + + amount = usage * multiplier * float64(size) + + } + + } else { + + amount = usage * multiplier + + } + + // else, resType is server + } else { + + // check if in bundle for amounts, get bundle value times the usage and use actual.cycle.skus as an extra multiplier + if q, exists := bundle.SkuPrices[sku]; !exists { + + continue + + } else { + + // quantity to float64 + if k := reflect.ValueOf(q); k.Kind() == reflect.Float64 { + + quantity = q.(float64) + + } else { + + v, _ := q.(json.Number).Int64() + quantity = float64(v) + + } + + amount = usage * multiplier * quantity + + } + + } + + // create the cost elemt + costSku := make(datamodels.JSONdb) + costSku["sku"] = sku + costSku["sku-state"] = *cycles[i].State + + // get cost + costSku["sku-cost"] = amount * skuPrice + + // get discount as % of cost + costSku["sku-discount"] = costSku["sku-cost"].(float64) * skuDiscount + + // get the net cost as cost-discount + costSku["sku-net"] = costSku["sku-cost"].(float64) - costSku["sku-discount"].(float64) + + // Add the cost to the collection + costSkuTotal = append(costSkuTotal, costSku) + + } + + } + + // place the costbreakup in place + costBreakup["costBreakup"] = costSkuTotal + + if costBreakup["costBreakup"] == nil { + + l.Warning.Printf("[DB] Something went wrong in the cost breakup generation. Skipping this element...\n") + + continue + + } + + // Let's create the total cost + costBreakup["totalFromSku"] = float64(0) + for _, c := range costBreakup["costBreakup"].([]datamodels.JSONdb) { + + costBreakup["totalFromSku"] = costBreakup["totalFromSku"].(float64) + c["sku-net"].(float64) + + } + + costBreakup["appliedDiscount"] = costBreakup["totalFromSku"].(float64) * float64(plan.Discount) + costBreakup["netTotal"] = costBreakup["totalFromSku"].(float64) - costBreakup["appliedDiscount"].(float64) + + var use models.CDRReport + use.Cost = costBreakup + use.Metadata = u.Metadata + use.ResourceID = u.ResourceID + use.ResourceName = u.ResourceName + use.ResourceType = u.ResourceType + use.Unit = u.Unit + use.UsageBreakup = u.UsageBreakup + + usages = append(usages, &use) + + } + + cdr.AccountID = report.AccountID + cdr.TimeFrom = report.TimeFrom + cdr.TimeTo = report.TimeTo + cdr.Usage = usages + + if e = d.AddRecord(cdr); e != nil { + + l.Warning.Printf("[DB] Something went wrong while saving the CDR record in the system. Error: %v\n", e) + + return + + } + + l.Trace.Printf("[DB] UDR processed and transformed into CDR and saved in the system successfully .\n") + + d.Pipe <- cdr + + l.Trace.Printf("[DB] CDR transmited to the Credit Manager successfully .\n") + + totalTime += float64(time.Now().UnixNano() - now) + totalCount++ + + d.Metrics["count"].With(prometheus.Labels{"type": "Total UDRs transformed to CDRs"}).Inc() + + d.Metrics["time"].With(prometheus.Labels{"type": "CDRs average generation time"}).Set(totalTime / float64(totalCount) / float64(time.Millisecond)) + + return + +} + +// getNiceFloat job is to turn the ugly float64 provided into a "nice looking" +// one according to the scale set, so we move from a floating coma number into +// a fixed coma number. +// Parameters: +// - i: the ugly floating coma number. +// Returns: +// - o: the "nice looking" fixed coma float. +func (d *DbParameter) getNiceFloat(i float64) (o float64) { + + min := float64(float64(1) / float64(scaler)) + + if diff := math.Abs(i - min); diff < min { + + o = float64(0) + + } else { + + o = float64(math.Round(i*scaler) / scaler) + + } + + return + +} diff --git a/services/cdr/server/kafka.go b/services/cdr/server/kafka.go new file mode 100644 index 0000000..373f687 --- /dev/null +++ b/services/cdr/server/kafka.go @@ -0,0 +1,311 @@ +package main + +import ( + "context" + "crypto/tls" + "reflect" + "strconv" + "time" + + "github.com/remeh/sizedwaitgroup" + "github.com/segmentio/encoding/json" + + "github.com/prometheus/client_golang/prometheus" + kafka "github.com/segmentio/kafka-go" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaFunction func(*dbManager.DbParameter, interface{}) error + +type kafkaHandlerConf struct { + in []kafkaPackage + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + model interface{} + function kafkaFunction + channel chan interface{} + saveDB bool +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(db *dbManager.DbParameter, monit *statusManager.StatusManager, kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.in != nil { + + monit.InitEndpoint("kafka-receiver") + + for _, p := range kH.in { + + go kafkaReceiver(db, monit, p.topic, p.partition, p.model, p.function, p.saveDB) + + } + } + + if kH.out != nil { + + monit.InitEndpoint("kafka-sender") + + for _, p := range kH.out { + + go kafkaSender(db, monit, p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaReceiver is the abstracted interface used to receive JSON data from kafka. +// The functions assumes that by default anything that comes from the kafka topic +// and validates against a specific data model has to be added to the db. +// Besides that it has the option to call an external function to interact with +// the data before putting it in the db. +// Parameters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - m: model to validate data against. +// - f: optional external function for more functionality. +// - saveDB: bool to control is the received data needs to be saved in the db. +func kafkaReceiver(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, m interface{}, f kafkaFunction, saveDB bool) { + + l.Trace.Printf("[KAFKA] Initializing kafka receiver for topic: %v.\n", t) + + conf := kafka.ReaderConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Partition: p, + MinBytes: cfg.Kafka.MinBytes, + MaxBytes: cfg.Kafka.MaxBytes, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + r := kafka.NewReader(conf) + defer r.Close() + + if e := r.SetOffset(cfg.Kafka.Offset); e != nil { + + l.Warning.Printf("[KAFKA] There was a problem when setting the offset, stopping the kafka handler NOW. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream offset"}).Inc() + + return + + } + + swg := sizedwaitgroup.New(8) + + for { + + rm, e := r.ReadMessage(context.Background()) + + if e != nil { + + l.Warning.Printf("[KAFKA] Error detected in the kafka stream. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream"}).Inc() + + continue + + } + + // Goroutines start + swg.Add() + go func() { + + callTime := time.Now() + monit.APIHit("kafka-receiver", callTime) + + defer swg.Done() + + o := reflect.New(reflect.TypeOf(m)).Interface() + + if e := json.Unmarshal(rm.Value, &o); e == nil { + + l.Info.Printf("[KAFKA] Relevant information detected in the stream: Topic: %v, partition: %v.\n", t, p) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object received"}).Inc() + + if f != nil { + + l.Info.Printf("[KAFKA] Function for specialized work detected. Starting its processing.\n") + + if err := f(db, o); err != nil { + + l.Warning.Printf("[KAFKA] There was a problem processing the model's specific function. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: linked function"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: linked function"}).Inc() + + } + + } + + if saveDB { + + l.Info.Printf("[KAFKA] Saving procesed record in the database.\n") + + if err := db.Db.Create(o).Error; err != nil { + + l.Warning.Printf("[KAFKA] There was a problem adding the record into the database. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: db saving"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object db saved"}).Inc() + + } + + } + + } else { + + l.Warning.Printf("[KAFKA] The information in the stream does not fit the expected model, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream-rubish"}).Inc() + + } + + monit.APIHitDone("kafka-receiver", callTime) + + }() + + } + +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + l.Info.Printf("[KAFKA] The channel has problems or has been closed.\n") + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: channel"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + callTime := time.Now() + monit.APIHit("kafka-sender", callTime) + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: stream"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "OK: object sent"}).Inc() + + } + + monit.APIHitDone("kafka-sender", callTime) + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: JSON Marshalling"}).Inc() + + } + + }() + + } + +} diff --git a/services/cdr/server/main.go b/services/cdr/server/main.go new file mode 100644 index 0000000..7ecd397 --- /dev/null +++ b/services/cdr/server/main.go @@ -0,0 +1,176 @@ +package main + +import ( + "crypto/tls" + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/services/cdr/server/metrics.go b/services/cdr/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/services/cdr/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/services/cdr/server/security.go b/services/cdr/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/services/cdr/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/services/cdr/server/service.go b/services/cdr/server/service.go new file mode 100644 index 0000000..898e442 --- /dev/null +++ b/services/cdr/server/service.go @@ -0,0 +1,157 @@ +package main + +import ( + "net/http" + "net/url" + "strings" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/statusManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/triggerManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/usageManager" + udrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,...,N have to be customized + db := dbStart(&models.CDRRecord{}, &models.CReport{}) + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + // cache linked to the dbParameter + db.Cache = cacheStart(db.Metrics["cache"]) + + // In case of needed, here is where kafka support is started + // The functions needs to be customized accordingly to the needs of the service + // And the parts of the service that might need to send messages need to get + // the channel + db.Pipe = kafkaStart(db, mon) + + //bp := getBasePath() + uc := udrClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["udr"], + Path: udrClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + // Parts of the service HERE + t := triggerManager.New(db, mon, uc) + u := usageManager.New(db, mon) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + TriggerManagementAPI: t, + UsageManagementAPI: u, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Parameters: +// - db: DbPAramenter reference for interaction with the db. +// - mon: statusManager parameter reference to interact with the statusManager +// subsystem +// Returns: +// - ch: a interface{} channel to be able to send thing through the kafka topic generated. +func kafkaStart(db *dbManager.DbParameter, mon *statusManager.StatusManager) (ch chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + f := func(db *dbManager.DbParameter, model interface{}) (e error) { + + //TODO: Figure out a way to get the Bearer token from the http header somehow + if e = db.ProcessUDR(*model.(*udrModels.UReport), ""); e != nil { + + l.Warning.Printf("[KAFKA] There was an error while apliying the linked function. Error: %v\n", e) + + db.Metrics["count"].With(prometheus.Labels{"type": "UDR processing FAILED"}).Inc() + + db.Metrics["count"].With(prometheus.Labels{"type": "UDR processing FAILED for Account: " + (model.(*udrModels.UReport)).AccountID}).Inc() + + } else { + + l.Trace.Printf("[KAFKA] Aplication of the linked function done succesfully.\n") + + } + + return + + } + + ch = make(chan interface{}, 500) + + handler := kafkaHandlerConf{ + in: []kafkaPackage{ + { + topic: cfg.Kafka.TopicsIn[0], + model: udrModels.UReport{}, + function: f, + saveDB: false, + }, + }, + out: []kafkaPackage{ + { + topic: cfg.Kafka.TopicsOut[0], + channel: ch, + }, + }, + } + + kafkaHandler(db, mon, handler) + + return + +} diff --git a/services/cdr/server/statusManager/statusManager.go b/services/cdr/server/statusManager/statusManager.go new file mode 100644 index 0000000..5185762 --- /dev/null +++ b/services/cdr/server/statusManager/statusManager.go @@ -0,0 +1,325 @@ +package statusManager + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 + mutex *sync.Mutex +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + mutex = &sync.Mutex{} + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + avgTime[key] = t.UnixNano() + mutex.Unlock() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + previous, exists := avgTime[key] + mutex.Unlock() + + if exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + mutex.Lock() + delete(avgTime, key) + mutex.Unlock() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/services/cdr/server/triggerManager/triggerManager.go b/services/cdr/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..b6f6adc --- /dev/null +++ b/services/cdr/server/triggerManager/triggerManager.go @@ -0,0 +1,241 @@ +package triggerManager + +import ( + "context" + "net/http" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/remeh/sizedwaitgroup" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/statusManager" + udrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client" + udrUsage "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client/usage_management" + udrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + l "gitlab.com/cyclops-utilities/logging" +) + +// TriggerManager is the struct defined to group and contain all the methods +// that interact with the trigger subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +// - udrConfig: a UDR client config reference to interact with UDR service. +type TriggerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager + udrConfig udrClient.Config +} + +// New is the function to create the struct TriggerManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// Returns: +// - TriggerManager: struct to interact with TriggerManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, c udrClient.Config) *TriggerManager { + + l.Trace.Printf("[TriggerManager] Generating new triggerManager.\n") + + monit.InitEndpoint("trigger") + + return &TriggerManager{ + db: db, + monit: monit, + udrConfig: c, + } + +} + +func (m *TriggerManager) getClient(param *http.Request) *udrClient.UDRManagementAPI { + + config := m.udrConfig + + if len(param.Header.Get("Authorization")) > 0 { + + token := strings.Fields(param.Header.Get("Authorization"))[1] + + config.AuthInfo = httptransport.BearerToken(token) + + } + + u := udrClient.New(config) + + return u + +} + +// ExecTransformation (Swagger func) is the function behind the +// /trigger/execTransformation endpoint. +// It function is to serve as a backup functionality to trigger the manual +// transformation of the UDR into CDRs. +func (m *TriggerManager) ExecTransformation(ctx context.Context, params trigger_management.ExecTransformationParams) middleware.Responder { + + l.Trace.Printf("[Trigger] ExecSample endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + var from, to strfmt.DateTime + var now time.Time + var cdrCount int64 + + if params.From != nil && params.To != nil { + + l.Trace.Printf("[TriggerManager] Preriod for compactation provided by params: [ %v ] to [ %v ].\n", params.From, params.To) + + from = *params.From + to = *params.To + + } else { + + if params.FastMode != nil && *params.FastMode { + + switch now = time.Now(); now.Minute() { + + case 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15: + + f := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 45, 0, 0, time.UTC) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, time.UTC)) + + from = strfmt.DateTime(f.Add(time.Minute * -60)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH(-1):45-HH:00 in day(-1?).\n") + + case 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 15, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH:00-HH:15.\n") + + case 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 15, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 30, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH:15-HH:30.\n") + + case 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 0: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 30, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 45, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH:30-HH:45.\n") + + } + + } else { + + switch now = time.Now(); now.Hour() { + + case 0, 1, 2, 3, 4, 5, 6, 7: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day()-1, 16, 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Period for transformation: 16:00-24:00 in day -1.\n") + + case 8, 9, 10, 11, 12, 13, 14, 15: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 8, 0, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Period for transformation: 00:00-08:00.\n") + + case 16, 17, 18, 19, 20, 21, 22, 23: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 8, 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 16, 0, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Period for transformation: 08:00-16:00.\n") + + } + + } + + } + + udrClient := m.getClient(params.HTTPRequest) + + udrParams := udrUsage.NewGetSystemUsageParams().WithFrom(&from).WithTo(&to) + + r, e := udrClient.UsageManagement.GetSystemUsage(ctx, udrParams) + + if e != nil { + + l.Warning.Printf("[TriggerManager] There was a problem while importing data from UDR. Error: %v", e) + + s := "UDRs import failed: " + e.Error() + returnValueError := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/trigger/execTransformation"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecTransformationInternalServerError().WithPayload(&returnValueError) + + } + + swg := sizedwaitgroup.New(8) + + for id := range r.Payload { + + // Goroutines start + swg.Add() + go func(udrIN *udrModels.UReport) { + + udr := *udrIN + defer swg.Done() + + token := "" + + if len(params.HTTPRequest.Header.Get("Authorization")) > 0 { + + token = strings.Fields(params.HTTPRequest.Header.Get("Authorization"))[1] + + } + + e := m.db.ProcessUDR(udr, token) + + if e != nil { + + m.db.Metrics["count"].With(prometheus.Labels{"type": "UDR processing FAILED"}).Inc() + + m.db.Metrics["count"].With(prometheus.Labels{"type": "UDR processing FAILED for Account: " + r.Payload[id].AccountID}).Inc() + + l.Warning.Printf("[TriggerManager] There was a problem while processing the UDR Report, skipping this one. Error: %v", e) + + } else { + + cdrCount++ + + } + + }(r.Payload[id]) + + } + + swg.Wait() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "CDRs triggered generation time"}).Set(float64(callTime.UnixNano()-now.UnixNano()) / float64(time.Millisecond)) + + m.db.Metrics["count"].With(prometheus.Labels{"type": "UDRs transformed to CDRs"}).Set(float64(cdrCount)) + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/trigger/execTransformation"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecTransformationOK() + +} diff --git a/services/cdr/server/usageManager/usageManager.go b/services/cdr/server/usageManager/usageManager.go new file mode 100644 index 0000000..f868986 --- /dev/null +++ b/services/cdr/server/usageManager/usageManager.go @@ -0,0 +1,237 @@ +package usageManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/restapi/operations/usage_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// UsageManager is the struct defined to group and contain all the methods +// that interact with the usage endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type UsageManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct UsageManager that grant +// access to the methods to interact with the usage endpoint. +// Parameters: +// - db: a reference to the DbParameter to be able to interact with the db methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// Returns: +// - UsageManager: struct to interact with the usage endpoint functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *UsageManager { + + l.Trace.Printf("[UsageManager] Generating new ResellerManager.\n") + + monit.InitEndpoint("usage") + + return &UsageManager{ + db: db, + monit: monit, + } + +} + +// GetSystemUsage (Swagger func) is the function behind the (GET) endpoint +// /usage +// Its job is to retrieve the usage report given a certain time-window and with +// the posibility of filtering by metric. +func (m *UsageManager) GetSystemUsage(ctx context.Context, params usage_management.GetSystemUsageParams) middleware.Responder { + + l.Trace.Printf("[UsageManager] GetSystemUsage endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("usage", callTime) + + var from, to strfmt.DateTime + var usage []*models.CReport + var e error + + metric := "" + + if params.Metric != nil { + + metric = *params.Metric + + } + + if params.From != nil { + + from = *params.From + + } + + if params.To != nil { + + to = *params.To + + } + + if params.Idlist != nil { + + if usage, e = m.db.GetUsages(*params.Idlist, metric, from, to); e == nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage"}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetSystemUsageOK().WithPayload(usage) + + } + + } else { + + if usage, e = m.db.GetUsage("", metric, from, to); e == nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage"}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetSystemUsageOK().WithPayload(usage) + + } + + } + + s := "There was an error in the DB operation: " + e.Error() + returnValueError := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/usage"}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetSystemUsageInternalServerError().WithPayload(&returnValueError) + +} + +// GetUsage (Swagger func) is the function behind the (GET) endpoint +// /usage/{id} +// Its job is to retrieve the usage report of the given account during the +// defined time-window, with the posibility of filtering by metric. +func (m *UsageManager) GetUsage(ctx context.Context, params usage_management.GetUsageParams) middleware.Responder { + + l.Trace.Printf("[UsageManager] GetUsage endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("usage", callTime) + + var from, to strfmt.DateTime + + metric := "" + + if params.Metric != nil { + + metric = *params.Metric + + } + + if params.From != nil { + + from = *params.From + + } + + if params.To != nil { + + to = *params.To + + } + + usage, e := m.db.GetUsage(params.ID, metric, from, to) + + if e == nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageOK().WithPayload(usage) + + } + + s := "There was an error in the DB operation: " + e.Error() + returnValueError := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/usage/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageInternalServerError().WithPayload(&returnValueError) + +} + +// GetUsageSummary (Swagger func) is the function behind the (GET) endpoint +// /usage/summary/{id} +// Its job is to retrieve easy to use for the UI usage report of all the products +// linked to the reseller account provided during the defined time-window. +func (m *UsageManager) GetUsageSummary(ctx context.Context, params usage_management.GetUsageSummaryParams) middleware.Responder { + + l.Trace.Printf("[UsageManager] GetUsageSummary endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("usage", callTime) + + var from, to strfmt.DateTime + + if params.From != nil { + + from = *params.From + + } else { + + from = strfmt.DateTime(time.Date(callTime.Year(), callTime.Month(), callTime.Day(), 0, 0, 0, 0, time.UTC)) + + } + + if params.To != nil { + + to = *params.To + + } else { + + t := time.Date(callTime.Year(), callTime.Month(), callTime.Day(), 0, 0, 0, 0, time.UTC) + to = strfmt.DateTime(t.AddDate(0, 0, -1)) + + } + + usage, e := m.db.GetUsageSummary(params.ID, from, to) + + if e == nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage/summary/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageSummaryOK().WithPayload(usage) + + } + + s := "There was an error in the DB operation: " + e.Error() + returnValueError := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/usage/summary/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageSummaryInternalServerError().WithPayload(&returnValueError) + +} diff --git a/services/cdr/swagger.yaml b/services/cdr/swagger.yaml new file mode 100644 index 0000000..ae18b5e --- /dev/null +++ b/services/cdr/swagger.yaml @@ -0,0 +1,387 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v1.0" +info: + description: An API which supports creation, deletion, listing etc of CDR + version: "1.0.0" + title: CDR Management API + contact: + email: "diego@cyclops-labs.io" + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + - name: usageManagement + description: Actions relating to the usage reporting of the accounts of the system + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - kafka-receiver + - kafka-sender + - status + - trigger + - usage + required: true + description: Id of the endpoint to be checked + + /trigger/transform: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Transformation of UDR to CDR task trigger + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: execTransformation + responses: + '200': + description: Transformation task executed successfully. + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: from + in: query + description: Datetime from which to get the usage report + type: string + format: datetime + - name: to + in: query + description: Datetime until which to get the usage report + type: string + format: datetime + - name: fast_mode + in: query + description: Switch for using 15m boundaries instead of 8h + type: boolean + + /usage: + get: + tags: + - usageManagement + produces: + - application/json + summary: Detailed report covering all accounts within the specified time window + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getSystemUsage + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/CReport" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: from + in: query + description: Datetime from which to get the usage report + type: string + format: datetime + - name: to + in: query + description: Datetime until which to get the usage report + type: string + format: datetime + - name: metric + in: query + description: Metric(s) to get the usage report + type: string + - name: idlist + in: query + description: List of ids to be queried + type: string + /usage/{id}: + get: + tags: + - usageManagement + produces: + - application/json + summary: Detailed report covering of the account associated with the id within the specified time window + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getUsage + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/CReport" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the account to be checked + required: true + type: string + - name: from + in: query + description: Datetime from which to get the usage report + type: string + format: datetime + - name: to + in: query + description: Datetime until which to get the usage report + type: string + format: datetime + - name: metric + in: query + description: Metric(s) to get the usage report + type: string + + /usage/summary/{id}: + get: + tags: + - usageManagement + produces: + - application/json + summary: Summary report meant for the UI for the resources linked to the ResellerID provided within the specified time window + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getUsageSummary + responses: + '200': + description: Description of a successfully operation + schema: + $ref: "#/definitions/UISummary" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the reseller to be checked + required: true + type: string + - name: from + in: query + description: Datetime from which to get the usage report + type: string + format: datetime + - name: to + in: query + description: Datetime until which to get the usage report + type: string + format: datetime + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + ItemCreatedResponse: + properties: + ApiLink: + type: string + Message: + type: string + Metadata: + type: object + x-go-type: + import: + package: "gitlab.com/cyclops-enterprise/datamodels" + type: JSONdb + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + + CDRRecord: + type: object + properties: + AccountId: + type: string + x-go-custom-tag: gorm:"index" + Cost: + $ref: '#/definitions/Metadata' + x-go-custom-tag: gorm:"type:jsonb" + Metadata: + $ref: '#/definitions/Metadata' + x-go-custom-tag: gorm:"type:jsonb" + ResourceId: + type: string + ResourceName: + type: string + ResourceType: + type: string + TimeFrom: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + TimeTo: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + Unit: + type: string + UsageBreakup: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + + CDRReport: + type: object + properties: + Cost: + $ref: '#/definitions/Metadata' + x-go-custom-tag: gorm:"type:jsonb" + Metadata: + $ref: '#/definitions/Metadata' + x-go-custom-tag: gorm:"type:jsonb" + ResourceId: + type: string + ResourceName: + type: string + ResourceType: + type: string + Unit: + type: string + UsageBreakup: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + + CReport: + type: object + properties: + AccountId: + type: string + x-go-custom-tag: gorm:"index" + TimeFrom: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + TimeTo: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + Usage: + type: array + x-go-custom-tag: gorm:"-" + items: + $ref: "#/definitions/CDRReport" + + UISummary: + type: object + properties: + AccountId: + type: string + TimeFrom: + type: string + format: datetime + TimeTo: + type: string + format: datetime + UsageBreakup: + $ref: '#/definitions/Metadata' diff --git a/services/credit-system/README.md b/services/credit-system/README.md new file mode 100644 index 0000000..54c4f02 --- /dev/null +++ b/services/credit-system/README.md @@ -0,0 +1,26 @@ +# CREDIT SYSTEM SERVICE + +Cyclops Engine's Credit System Service implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + diff --git a/services/credit-system/client/account_management/account_management_client.go b/services/credit-system/client/account_management/account_management_client.go new file mode 100644 index 0000000..3c8df2d --- /dev/null +++ b/services/credit-system/client/account_management/account_management_client.go @@ -0,0 +1,178 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the account management client +type API interface { + /* + CreateAccount creates a new account in the system*/ + CreateAccount(ctx context.Context, params *CreateAccountParams) (*CreateAccountCreated, error) + /* + DisableAccount disables the account with the id provided in the system*/ + DisableAccount(ctx context.Context, params *DisableAccountParams) (*DisableAccountOK, error) + /* + EnableAccount enables the account with the id provided in the system*/ + EnableAccount(ctx context.Context, params *EnableAccountParams) (*EnableAccountOK, error) + /* + GetAccountStatus basics status of the account with the id provided in the system*/ + GetAccountStatus(ctx context.Context, params *GetAccountStatusParams) (*GetAccountStatusOK, error) + /* + ListAccounts lists of the accounts in the system*/ + ListAccounts(ctx context.Context, params *ListAccountsParams) (*ListAccountsOK, error) +} + +// New creates a new account management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for account management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +CreateAccount creates a new account in the system +*/ +func (a *Client) CreateAccount(ctx context.Context, params *CreateAccountParams) (*CreateAccountCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "createAccount", + Method: "GET", + PathPattern: "/account/create/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &CreateAccountReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*CreateAccountCreated), nil + +} + +/* +DisableAccount disables the account with the id provided in the system +*/ +func (a *Client) DisableAccount(ctx context.Context, params *DisableAccountParams) (*DisableAccountOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "disableAccount", + Method: "POST", + PathPattern: "/account/disable/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &DisableAccountReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*DisableAccountOK), nil + +} + +/* +EnableAccount enables the account with the id provided in the system +*/ +func (a *Client) EnableAccount(ctx context.Context, params *EnableAccountParams) (*EnableAccountOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "enableAccount", + Method: "POST", + PathPattern: "/account/enable/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &EnableAccountReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*EnableAccountOK), nil + +} + +/* +GetAccountStatus basics status of the account with the id provided in the system +*/ +func (a *Client) GetAccountStatus(ctx context.Context, params *GetAccountStatusParams) (*GetAccountStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getAccountStatus", + Method: "GET", + PathPattern: "/account/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetAccountStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetAccountStatusOK), nil + +} + +/* +ListAccounts lists of the accounts in the system +*/ +func (a *Client) ListAccounts(ctx context.Context, params *ListAccountsParams) (*ListAccountsOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listAccounts", + Method: "GET", + PathPattern: "/account/list", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListAccountsReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListAccountsOK), nil + +} diff --git a/services/credit-system/client/account_management/create_account_parameters.go b/services/credit-system/client/account_management/create_account_parameters.go new file mode 100644 index 0000000..65f1c4f --- /dev/null +++ b/services/credit-system/client/account_management/create_account_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewCreateAccountParams creates a new CreateAccountParams object +// with the default values initialized. +func NewCreateAccountParams() *CreateAccountParams { + var () + return &CreateAccountParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewCreateAccountParamsWithTimeout creates a new CreateAccountParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewCreateAccountParamsWithTimeout(timeout time.Duration) *CreateAccountParams { + var () + return &CreateAccountParams{ + + timeout: timeout, + } +} + +// NewCreateAccountParamsWithContext creates a new CreateAccountParams object +// with the default values initialized, and the ability to set a context for a request +func NewCreateAccountParamsWithContext(ctx context.Context) *CreateAccountParams { + var () + return &CreateAccountParams{ + + Context: ctx, + } +} + +// NewCreateAccountParamsWithHTTPClient creates a new CreateAccountParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewCreateAccountParamsWithHTTPClient(client *http.Client) *CreateAccountParams { + var () + return &CreateAccountParams{ + HTTPClient: client, + } +} + +/*CreateAccountParams contains all the parameters to send to the API endpoint +for the create account operation typically these are written to a http.Request +*/ +type CreateAccountParams struct { + + /*ID + Id of the account to be created + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the create account params +func (o *CreateAccountParams) WithTimeout(timeout time.Duration) *CreateAccountParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create account params +func (o *CreateAccountParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create account params +func (o *CreateAccountParams) WithContext(ctx context.Context) *CreateAccountParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create account params +func (o *CreateAccountParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create account params +func (o *CreateAccountParams) WithHTTPClient(client *http.Client) *CreateAccountParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create account params +func (o *CreateAccountParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the create account params +func (o *CreateAccountParams) WithID(id string) *CreateAccountParams { + o.SetID(id) + return o +} + +// SetID adds the id to the create account params +func (o *CreateAccountParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateAccountParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/account_management/create_account_responses.go b/services/credit-system/client/account_management/create_account_responses.go new file mode 100644 index 0000000..e062953 --- /dev/null +++ b/services/credit-system/client/account_management/create_account_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// CreateAccountReader is a Reader for the CreateAccount structure. +type CreateAccountReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateAccountReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewCreateAccountCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 409: + result := NewCreateAccountConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewCreateAccountInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewCreateAccountCreated creates a CreateAccountCreated with default headers values +func NewCreateAccountCreated() *CreateAccountCreated { + return &CreateAccountCreated{} +} + +/*CreateAccountCreated handles this case with default header values. + +Account created, provided information of the new item created +*/ +type CreateAccountCreated struct { + Payload *models.AccountStatus +} + +func (o *CreateAccountCreated) Error() string { + return fmt.Sprintf("[GET /account/create/{id}][%d] createAccountCreated %+v", 201, o.Payload) +} + +func (o *CreateAccountCreated) GetPayload() *models.AccountStatus { + return o.Payload +} + +func (o *CreateAccountCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.AccountStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateAccountConflict creates a CreateAccountConflict with default headers values +func NewCreateAccountConflict() *CreateAccountConflict { + return &CreateAccountConflict{} +} + +/*CreateAccountConflict handles this case with default header values. + +The account with the id provided already exist +*/ +type CreateAccountConflict struct { + Payload *models.ErrorResponse +} + +func (o *CreateAccountConflict) Error() string { + return fmt.Sprintf("[GET /account/create/{id}][%d] createAccountConflict %+v", 409, o.Payload) +} + +func (o *CreateAccountConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateAccountConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateAccountInternalServerError creates a CreateAccountInternalServerError with default headers values +func NewCreateAccountInternalServerError() *CreateAccountInternalServerError { + return &CreateAccountInternalServerError{} +} + +/*CreateAccountInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type CreateAccountInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *CreateAccountInternalServerError) Error() string { + return fmt.Sprintf("[GET /account/create/{id}][%d] createAccountInternalServerError %+v", 500, o.Payload) +} + +func (o *CreateAccountInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateAccountInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/account_management/disable_account_parameters.go b/services/credit-system/client/account_management/disable_account_parameters.go new file mode 100644 index 0000000..3c69a09 --- /dev/null +++ b/services/credit-system/client/account_management/disable_account_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDisableAccountParams creates a new DisableAccountParams object +// with the default values initialized. +func NewDisableAccountParams() *DisableAccountParams { + var () + return &DisableAccountParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewDisableAccountParamsWithTimeout creates a new DisableAccountParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewDisableAccountParamsWithTimeout(timeout time.Duration) *DisableAccountParams { + var () + return &DisableAccountParams{ + + timeout: timeout, + } +} + +// NewDisableAccountParamsWithContext creates a new DisableAccountParams object +// with the default values initialized, and the ability to set a context for a request +func NewDisableAccountParamsWithContext(ctx context.Context) *DisableAccountParams { + var () + return &DisableAccountParams{ + + Context: ctx, + } +} + +// NewDisableAccountParamsWithHTTPClient creates a new DisableAccountParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewDisableAccountParamsWithHTTPClient(client *http.Client) *DisableAccountParams { + var () + return &DisableAccountParams{ + HTTPClient: client, + } +} + +/*DisableAccountParams contains all the parameters to send to the API endpoint +for the disable account operation typically these are written to a http.Request +*/ +type DisableAccountParams struct { + + /*ID + Id of the account to be disabled + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the disable account params +func (o *DisableAccountParams) WithTimeout(timeout time.Duration) *DisableAccountParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the disable account params +func (o *DisableAccountParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the disable account params +func (o *DisableAccountParams) WithContext(ctx context.Context) *DisableAccountParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the disable account params +func (o *DisableAccountParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the disable account params +func (o *DisableAccountParams) WithHTTPClient(client *http.Client) *DisableAccountParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the disable account params +func (o *DisableAccountParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the disable account params +func (o *DisableAccountParams) WithID(id string) *DisableAccountParams { + o.SetID(id) + return o +} + +// SetID adds the id to the disable account params +func (o *DisableAccountParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *DisableAccountParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/account_management/disable_account_responses.go b/services/credit-system/client/account_management/disable_account_responses.go new file mode 100644 index 0000000..6071168 --- /dev/null +++ b/services/credit-system/client/account_management/disable_account_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// DisableAccountReader is a Reader for the DisableAccount structure. +type DisableAccountReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DisableAccountReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDisableAccountOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewDisableAccountNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewDisableAccountInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewDisableAccountOK creates a DisableAccountOK with default headers values +func NewDisableAccountOK() *DisableAccountOK { + return &DisableAccountOK{} +} + +/*DisableAccountOK handles this case with default header values. + +Status information of the account with provided id in the system after the operation succeded +*/ +type DisableAccountOK struct { + Payload *models.AccountStatus +} + +func (o *DisableAccountOK) Error() string { + return fmt.Sprintf("[POST /account/disable/{id}][%d] disableAccountOK %+v", 200, o.Payload) +} + +func (o *DisableAccountOK) GetPayload() *models.AccountStatus { + return o.Payload +} + +func (o *DisableAccountOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.AccountStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDisableAccountNotFound creates a DisableAccountNotFound with default headers values +func NewDisableAccountNotFound() *DisableAccountNotFound { + return &DisableAccountNotFound{} +} + +/*DisableAccountNotFound handles this case with default header values. + +The account with the id provided doesn't exist +*/ +type DisableAccountNotFound struct { + Payload *models.ErrorResponse +} + +func (o *DisableAccountNotFound) Error() string { + return fmt.Sprintf("[POST /account/disable/{id}][%d] disableAccountNotFound %+v", 404, o.Payload) +} + +func (o *DisableAccountNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *DisableAccountNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDisableAccountInternalServerError creates a DisableAccountInternalServerError with default headers values +func NewDisableAccountInternalServerError() *DisableAccountInternalServerError { + return &DisableAccountInternalServerError{} +} + +/*DisableAccountInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type DisableAccountInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *DisableAccountInternalServerError) Error() string { + return fmt.Sprintf("[POST /account/disable/{id}][%d] disableAccountInternalServerError %+v", 500, o.Payload) +} + +func (o *DisableAccountInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *DisableAccountInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/account_management/enable_account_parameters.go b/services/credit-system/client/account_management/enable_account_parameters.go new file mode 100644 index 0000000..e750cdc --- /dev/null +++ b/services/credit-system/client/account_management/enable_account_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewEnableAccountParams creates a new EnableAccountParams object +// with the default values initialized. +func NewEnableAccountParams() *EnableAccountParams { + var () + return &EnableAccountParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewEnableAccountParamsWithTimeout creates a new EnableAccountParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewEnableAccountParamsWithTimeout(timeout time.Duration) *EnableAccountParams { + var () + return &EnableAccountParams{ + + timeout: timeout, + } +} + +// NewEnableAccountParamsWithContext creates a new EnableAccountParams object +// with the default values initialized, and the ability to set a context for a request +func NewEnableAccountParamsWithContext(ctx context.Context) *EnableAccountParams { + var () + return &EnableAccountParams{ + + Context: ctx, + } +} + +// NewEnableAccountParamsWithHTTPClient creates a new EnableAccountParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewEnableAccountParamsWithHTTPClient(client *http.Client) *EnableAccountParams { + var () + return &EnableAccountParams{ + HTTPClient: client, + } +} + +/*EnableAccountParams contains all the parameters to send to the API endpoint +for the enable account operation typically these are written to a http.Request +*/ +type EnableAccountParams struct { + + /*ID + Id of the account to be enabled + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the enable account params +func (o *EnableAccountParams) WithTimeout(timeout time.Duration) *EnableAccountParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the enable account params +func (o *EnableAccountParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the enable account params +func (o *EnableAccountParams) WithContext(ctx context.Context) *EnableAccountParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the enable account params +func (o *EnableAccountParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the enable account params +func (o *EnableAccountParams) WithHTTPClient(client *http.Client) *EnableAccountParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the enable account params +func (o *EnableAccountParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the enable account params +func (o *EnableAccountParams) WithID(id string) *EnableAccountParams { + o.SetID(id) + return o +} + +// SetID adds the id to the enable account params +func (o *EnableAccountParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *EnableAccountParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/account_management/enable_account_responses.go b/services/credit-system/client/account_management/enable_account_responses.go new file mode 100644 index 0000000..034a82f --- /dev/null +++ b/services/credit-system/client/account_management/enable_account_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// EnableAccountReader is a Reader for the EnableAccount structure. +type EnableAccountReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *EnableAccountReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewEnableAccountOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewEnableAccountNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewEnableAccountInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewEnableAccountOK creates a EnableAccountOK with default headers values +func NewEnableAccountOK() *EnableAccountOK { + return &EnableAccountOK{} +} + +/*EnableAccountOK handles this case with default header values. + +Status information of the account with provided id in the system after the operation succeded +*/ +type EnableAccountOK struct { + Payload *models.AccountStatus +} + +func (o *EnableAccountOK) Error() string { + return fmt.Sprintf("[POST /account/enable/{id}][%d] enableAccountOK %+v", 200, o.Payload) +} + +func (o *EnableAccountOK) GetPayload() *models.AccountStatus { + return o.Payload +} + +func (o *EnableAccountOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.AccountStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewEnableAccountNotFound creates a EnableAccountNotFound with default headers values +func NewEnableAccountNotFound() *EnableAccountNotFound { + return &EnableAccountNotFound{} +} + +/*EnableAccountNotFound handles this case with default header values. + +The account with the id provided doesn't exist +*/ +type EnableAccountNotFound struct { + Payload *models.ErrorResponse +} + +func (o *EnableAccountNotFound) Error() string { + return fmt.Sprintf("[POST /account/enable/{id}][%d] enableAccountNotFound %+v", 404, o.Payload) +} + +func (o *EnableAccountNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *EnableAccountNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewEnableAccountInternalServerError creates a EnableAccountInternalServerError with default headers values +func NewEnableAccountInternalServerError() *EnableAccountInternalServerError { + return &EnableAccountInternalServerError{} +} + +/*EnableAccountInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type EnableAccountInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *EnableAccountInternalServerError) Error() string { + return fmt.Sprintf("[POST /account/enable/{id}][%d] enableAccountInternalServerError %+v", 500, o.Payload) +} + +func (o *EnableAccountInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *EnableAccountInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/account_management/get_account_status_parameters.go b/services/credit-system/client/account_management/get_account_status_parameters.go new file mode 100644 index 0000000..8c02219 --- /dev/null +++ b/services/credit-system/client/account_management/get_account_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetAccountStatusParams creates a new GetAccountStatusParams object +// with the default values initialized. +func NewGetAccountStatusParams() *GetAccountStatusParams { + var () + return &GetAccountStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetAccountStatusParamsWithTimeout creates a new GetAccountStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetAccountStatusParamsWithTimeout(timeout time.Duration) *GetAccountStatusParams { + var () + return &GetAccountStatusParams{ + + timeout: timeout, + } +} + +// NewGetAccountStatusParamsWithContext creates a new GetAccountStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetAccountStatusParamsWithContext(ctx context.Context) *GetAccountStatusParams { + var () + return &GetAccountStatusParams{ + + Context: ctx, + } +} + +// NewGetAccountStatusParamsWithHTTPClient creates a new GetAccountStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetAccountStatusParamsWithHTTPClient(client *http.Client) *GetAccountStatusParams { + var () + return &GetAccountStatusParams{ + HTTPClient: client, + } +} + +/*GetAccountStatusParams contains all the parameters to send to the API endpoint +for the get account status operation typically these are written to a http.Request +*/ +type GetAccountStatusParams struct { + + /*ID + Id of the account to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get account status params +func (o *GetAccountStatusParams) WithTimeout(timeout time.Duration) *GetAccountStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get account status params +func (o *GetAccountStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get account status params +func (o *GetAccountStatusParams) WithContext(ctx context.Context) *GetAccountStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get account status params +func (o *GetAccountStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get account status params +func (o *GetAccountStatusParams) WithHTTPClient(client *http.Client) *GetAccountStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get account status params +func (o *GetAccountStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get account status params +func (o *GetAccountStatusParams) WithID(id string) *GetAccountStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get account status params +func (o *GetAccountStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetAccountStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/account_management/get_account_status_responses.go b/services/credit-system/client/account_management/get_account_status_responses.go new file mode 100644 index 0000000..4332b0b --- /dev/null +++ b/services/credit-system/client/account_management/get_account_status_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetAccountStatusReader is a Reader for the GetAccountStatus structure. +type GetAccountStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetAccountStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetAccountStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetAccountStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetAccountStatusInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetAccountStatusOK creates a GetAccountStatusOK with default headers values +func NewGetAccountStatusOK() *GetAccountStatusOK { + return &GetAccountStatusOK{} +} + +/*GetAccountStatusOK handles this case with default header values. + +Status information of the account with provided id in the system +*/ +type GetAccountStatusOK struct { + Payload *models.AccountStatus +} + +func (o *GetAccountStatusOK) Error() string { + return fmt.Sprintf("[GET /account/status/{id}][%d] getAccountStatusOK %+v", 200, o.Payload) +} + +func (o *GetAccountStatusOK) GetPayload() *models.AccountStatus { + return o.Payload +} + +func (o *GetAccountStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.AccountStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetAccountStatusNotFound creates a GetAccountStatusNotFound with default headers values +func NewGetAccountStatusNotFound() *GetAccountStatusNotFound { + return &GetAccountStatusNotFound{} +} + +/*GetAccountStatusNotFound handles this case with default header values. + +The account with the id provided doesn't exist +*/ +type GetAccountStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetAccountStatusNotFound) Error() string { + return fmt.Sprintf("[GET /account/status/{id}][%d] getAccountStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetAccountStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetAccountStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetAccountStatusInternalServerError creates a GetAccountStatusInternalServerError with default headers values +func NewGetAccountStatusInternalServerError() *GetAccountStatusInternalServerError { + return &GetAccountStatusInternalServerError{} +} + +/*GetAccountStatusInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetAccountStatusInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetAccountStatusInternalServerError) Error() string { + return fmt.Sprintf("[GET /account/status/{id}][%d] getAccountStatusInternalServerError %+v", 500, o.Payload) +} + +func (o *GetAccountStatusInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetAccountStatusInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/account_management/list_accounts_parameters.go b/services/credit-system/client/account_management/list_accounts_parameters.go new file mode 100644 index 0000000..5c8618f --- /dev/null +++ b/services/credit-system/client/account_management/list_accounts_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListAccountsParams creates a new ListAccountsParams object +// with the default values initialized. +func NewListAccountsParams() *ListAccountsParams { + + return &ListAccountsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListAccountsParamsWithTimeout creates a new ListAccountsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListAccountsParamsWithTimeout(timeout time.Duration) *ListAccountsParams { + + return &ListAccountsParams{ + + timeout: timeout, + } +} + +// NewListAccountsParamsWithContext creates a new ListAccountsParams object +// with the default values initialized, and the ability to set a context for a request +func NewListAccountsParamsWithContext(ctx context.Context) *ListAccountsParams { + + return &ListAccountsParams{ + + Context: ctx, + } +} + +// NewListAccountsParamsWithHTTPClient creates a new ListAccountsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListAccountsParamsWithHTTPClient(client *http.Client) *ListAccountsParams { + + return &ListAccountsParams{ + HTTPClient: client, + } +} + +/*ListAccountsParams contains all the parameters to send to the API endpoint +for the list accounts operation typically these are written to a http.Request +*/ +type ListAccountsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list accounts params +func (o *ListAccountsParams) WithTimeout(timeout time.Duration) *ListAccountsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list accounts params +func (o *ListAccountsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list accounts params +func (o *ListAccountsParams) WithContext(ctx context.Context) *ListAccountsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list accounts params +func (o *ListAccountsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list accounts params +func (o *ListAccountsParams) WithHTTPClient(client *http.Client) *ListAccountsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list accounts params +func (o *ListAccountsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListAccountsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/account_management/list_accounts_responses.go b/services/credit-system/client/account_management/list_accounts_responses.go new file mode 100644 index 0000000..b8a5cd4 --- /dev/null +++ b/services/credit-system/client/account_management/list_accounts_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// ListAccountsReader is a Reader for the ListAccounts structure. +type ListAccountsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListAccountsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListAccountsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListAccountsInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListAccountsOK creates a ListAccountsOK with default headers values +func NewListAccountsOK() *ListAccountsOK { + return &ListAccountsOK{} +} + +/*ListAccountsOK handles this case with default header values. + +List of accounts in the system +*/ +type ListAccountsOK struct { + Payload []*models.AccountStatus +} + +func (o *ListAccountsOK) Error() string { + return fmt.Sprintf("[GET /account/list][%d] listAccountsOK %+v", 200, o.Payload) +} + +func (o *ListAccountsOK) GetPayload() []*models.AccountStatus { + return o.Payload +} + +func (o *ListAccountsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListAccountsInternalServerError creates a ListAccountsInternalServerError with default headers values +func NewListAccountsInternalServerError() *ListAccountsInternalServerError { + return &ListAccountsInternalServerError{} +} + +/*ListAccountsInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListAccountsInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListAccountsInternalServerError) Error() string { + return fmt.Sprintf("[GET /account/list][%d] listAccountsInternalServerError %+v", 500, o.Payload) +} + +func (o *ListAccountsInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListAccountsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/credit_management/add_consumption_parameters.go b/services/credit-system/client/credit_management/add_consumption_parameters.go new file mode 100644 index 0000000..a2d3d93 --- /dev/null +++ b/services/credit-system/client/credit_management/add_consumption_parameters.go @@ -0,0 +1,182 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewAddConsumptionParams creates a new AddConsumptionParams object +// with the default values initialized. +func NewAddConsumptionParams() *AddConsumptionParams { + var () + return &AddConsumptionParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewAddConsumptionParamsWithTimeout creates a new AddConsumptionParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewAddConsumptionParamsWithTimeout(timeout time.Duration) *AddConsumptionParams { + var () + return &AddConsumptionParams{ + + timeout: timeout, + } +} + +// NewAddConsumptionParamsWithContext creates a new AddConsumptionParams object +// with the default values initialized, and the ability to set a context for a request +func NewAddConsumptionParamsWithContext(ctx context.Context) *AddConsumptionParams { + var () + return &AddConsumptionParams{ + + Context: ctx, + } +} + +// NewAddConsumptionParamsWithHTTPClient creates a new AddConsumptionParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewAddConsumptionParamsWithHTTPClient(client *http.Client) *AddConsumptionParams { + var () + return &AddConsumptionParams{ + HTTPClient: client, + } +} + +/*AddConsumptionParams contains all the parameters to send to the API endpoint +for the add consumption operation typically these are written to a http.Request +*/ +type AddConsumptionParams struct { + + /*Amount + Amount to be decreased + + */ + Amount float64 + /*ID + Id of the account to be checked + + */ + ID string + /*Medium + Medium (cash/credit) to be used in the accounting + + */ + Medium string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the add consumption params +func (o *AddConsumptionParams) WithTimeout(timeout time.Duration) *AddConsumptionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add consumption params +func (o *AddConsumptionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add consumption params +func (o *AddConsumptionParams) WithContext(ctx context.Context) *AddConsumptionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add consumption params +func (o *AddConsumptionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add consumption params +func (o *AddConsumptionParams) WithHTTPClient(client *http.Client) *AddConsumptionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add consumption params +func (o *AddConsumptionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAmount adds the amount to the add consumption params +func (o *AddConsumptionParams) WithAmount(amount float64) *AddConsumptionParams { + o.SetAmount(amount) + return o +} + +// SetAmount adds the amount to the add consumption params +func (o *AddConsumptionParams) SetAmount(amount float64) { + o.Amount = amount +} + +// WithID adds the id to the add consumption params +func (o *AddConsumptionParams) WithID(id string) *AddConsumptionParams { + o.SetID(id) + return o +} + +// SetID adds the id to the add consumption params +func (o *AddConsumptionParams) SetID(id string) { + o.ID = id +} + +// WithMedium adds the medium to the add consumption params +func (o *AddConsumptionParams) WithMedium(medium string) *AddConsumptionParams { + o.SetMedium(medium) + return o +} + +// SetMedium adds the medium to the add consumption params +func (o *AddConsumptionParams) SetMedium(medium string) { + o.Medium = medium +} + +// WriteToRequest writes these params to a swagger request +func (o *AddConsumptionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param amount + qrAmount := o.Amount + qAmount := swag.FormatFloat64(qrAmount) + if qAmount != "" { + if err := r.SetQueryParam("amount", qAmount); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // path param medium + if err := r.SetPathParam("medium", o.Medium); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/credit_management/add_consumption_responses.go b/services/credit-system/client/credit_management/add_consumption_responses.go new file mode 100644 index 0000000..b02e6d4 --- /dev/null +++ b/services/credit-system/client/credit_management/add_consumption_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// AddConsumptionReader is a Reader for the AddConsumption structure. +type AddConsumptionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddConsumptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewAddConsumptionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewAddConsumptionNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewAddConsumptionInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewAddConsumptionOK creates a AddConsumptionOK with default headers values +func NewAddConsumptionOK() *AddConsumptionOK { + return &AddConsumptionOK{} +} + +/*AddConsumptionOK handles this case with default header values. + +Credit status of the account with the provided id +*/ +type AddConsumptionOK struct { + Payload *models.CreditStatus +} + +func (o *AddConsumptionOK) Error() string { + return fmt.Sprintf("[POST /{medium}/consume/{id}][%d] addConsumptionOK %+v", 200, o.Payload) +} + +func (o *AddConsumptionOK) GetPayload() *models.CreditStatus { + return o.Payload +} + +func (o *AddConsumptionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CreditStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddConsumptionNotFound creates a AddConsumptionNotFound with default headers values +func NewAddConsumptionNotFound() *AddConsumptionNotFound { + return &AddConsumptionNotFound{} +} + +/*AddConsumptionNotFound handles this case with default header values. + +The account with the id provided doesn't exist +*/ +type AddConsumptionNotFound struct { + Payload *models.ErrorResponse +} + +func (o *AddConsumptionNotFound) Error() string { + return fmt.Sprintf("[POST /{medium}/consume/{id}][%d] addConsumptionNotFound %+v", 404, o.Payload) +} + +func (o *AddConsumptionNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddConsumptionNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddConsumptionInternalServerError creates a AddConsumptionInternalServerError with default headers values +func NewAddConsumptionInternalServerError() *AddConsumptionInternalServerError { + return &AddConsumptionInternalServerError{} +} + +/*AddConsumptionInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type AddConsumptionInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *AddConsumptionInternalServerError) Error() string { + return fmt.Sprintf("[POST /{medium}/consume/{id}][%d] addConsumptionInternalServerError %+v", 500, o.Payload) +} + +func (o *AddConsumptionInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddConsumptionInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/credit_management/credit_management_client.go b/services/credit-system/client/credit_management/credit_management_client.go new file mode 100644 index 0000000..f66b873 --- /dev/null +++ b/services/credit-system/client/credit_management/credit_management_client.go @@ -0,0 +1,178 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the credit management client +type API interface { + /* + AddConsumption adds a consumption to the system*/ + AddConsumption(ctx context.Context, params *AddConsumptionParams) (*AddConsumptionOK, error) + /* + DecreaseCredit inserts a new reseller in the system*/ + DecreaseCredit(ctx context.Context, params *DecreaseCreditParams) (*DecreaseCreditOK, error) + /* + GetCredit credits status of the account with the provided id*/ + GetCredit(ctx context.Context, params *GetCreditParams) (*GetCreditOK, error) + /* + GetHistory credits history of the customer with id*/ + GetHistory(ctx context.Context, params *GetHistoryParams) (*GetHistoryOK, error) + /* + IncreaseCredit inserts a new reseller in the system*/ + IncreaseCredit(ctx context.Context, params *IncreaseCreditParams) (*IncreaseCreditOK, error) +} + +// New creates a new credit management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for credit management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +AddConsumption adds a consumption to the system +*/ +func (a *Client) AddConsumption(ctx context.Context, params *AddConsumptionParams) (*AddConsumptionOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "addConsumption", + Method: "POST", + PathPattern: "/{medium}/consume/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &AddConsumptionReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*AddConsumptionOK), nil + +} + +/* +DecreaseCredit inserts a new reseller in the system +*/ +func (a *Client) DecreaseCredit(ctx context.Context, params *DecreaseCreditParams) (*DecreaseCreditOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "decreaseCredit", + Method: "POST", + PathPattern: "/{medium}/available/decrease/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &DecreaseCreditReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*DecreaseCreditOK), nil + +} + +/* +GetCredit credits status of the account with the provided id +*/ +func (a *Client) GetCredit(ctx context.Context, params *GetCreditParams) (*GetCreditOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getCredit", + Method: "GET", + PathPattern: "/account/available/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetCreditReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetCreditOK), nil + +} + +/* +GetHistory credits history of the customer with id +*/ +func (a *Client) GetHistory(ctx context.Context, params *GetHistoryParams) (*GetHistoryOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getHistory", + Method: "GET", + PathPattern: "/history/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetHistoryReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetHistoryOK), nil + +} + +/* +IncreaseCredit inserts a new reseller in the system +*/ +func (a *Client) IncreaseCredit(ctx context.Context, params *IncreaseCreditParams) (*IncreaseCreditOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "increaseCredit", + Method: "POST", + PathPattern: "/{medium}/available/increase/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &IncreaseCreditReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*IncreaseCreditOK), nil + +} diff --git a/services/credit-system/client/credit_management/decrease_credit_parameters.go b/services/credit-system/client/credit_management/decrease_credit_parameters.go new file mode 100644 index 0000000..1392057 --- /dev/null +++ b/services/credit-system/client/credit_management/decrease_credit_parameters.go @@ -0,0 +1,182 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDecreaseCreditParams creates a new DecreaseCreditParams object +// with the default values initialized. +func NewDecreaseCreditParams() *DecreaseCreditParams { + var () + return &DecreaseCreditParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewDecreaseCreditParamsWithTimeout creates a new DecreaseCreditParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewDecreaseCreditParamsWithTimeout(timeout time.Duration) *DecreaseCreditParams { + var () + return &DecreaseCreditParams{ + + timeout: timeout, + } +} + +// NewDecreaseCreditParamsWithContext creates a new DecreaseCreditParams object +// with the default values initialized, and the ability to set a context for a request +func NewDecreaseCreditParamsWithContext(ctx context.Context) *DecreaseCreditParams { + var () + return &DecreaseCreditParams{ + + Context: ctx, + } +} + +// NewDecreaseCreditParamsWithHTTPClient creates a new DecreaseCreditParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewDecreaseCreditParamsWithHTTPClient(client *http.Client) *DecreaseCreditParams { + var () + return &DecreaseCreditParams{ + HTTPClient: client, + } +} + +/*DecreaseCreditParams contains all the parameters to send to the API endpoint +for the decrease credit operation typically these are written to a http.Request +*/ +type DecreaseCreditParams struct { + + /*Amount + Amount to be decreased + + */ + Amount float64 + /*ID + Id of the account to be checked + + */ + ID string + /*Medium + Medium (cash/credit) to be used in the accounting + + */ + Medium string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the decrease credit params +func (o *DecreaseCreditParams) WithTimeout(timeout time.Duration) *DecreaseCreditParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the decrease credit params +func (o *DecreaseCreditParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the decrease credit params +func (o *DecreaseCreditParams) WithContext(ctx context.Context) *DecreaseCreditParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the decrease credit params +func (o *DecreaseCreditParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the decrease credit params +func (o *DecreaseCreditParams) WithHTTPClient(client *http.Client) *DecreaseCreditParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the decrease credit params +func (o *DecreaseCreditParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAmount adds the amount to the decrease credit params +func (o *DecreaseCreditParams) WithAmount(amount float64) *DecreaseCreditParams { + o.SetAmount(amount) + return o +} + +// SetAmount adds the amount to the decrease credit params +func (o *DecreaseCreditParams) SetAmount(amount float64) { + o.Amount = amount +} + +// WithID adds the id to the decrease credit params +func (o *DecreaseCreditParams) WithID(id string) *DecreaseCreditParams { + o.SetID(id) + return o +} + +// SetID adds the id to the decrease credit params +func (o *DecreaseCreditParams) SetID(id string) { + o.ID = id +} + +// WithMedium adds the medium to the decrease credit params +func (o *DecreaseCreditParams) WithMedium(medium string) *DecreaseCreditParams { + o.SetMedium(medium) + return o +} + +// SetMedium adds the medium to the decrease credit params +func (o *DecreaseCreditParams) SetMedium(medium string) { + o.Medium = medium +} + +// WriteToRequest writes these params to a swagger request +func (o *DecreaseCreditParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param amount + qrAmount := o.Amount + qAmount := swag.FormatFloat64(qrAmount) + if qAmount != "" { + if err := r.SetQueryParam("amount", qAmount); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // path param medium + if err := r.SetPathParam("medium", o.Medium); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/credit_management/decrease_credit_responses.go b/services/credit-system/client/credit_management/decrease_credit_responses.go new file mode 100644 index 0000000..6cc524e --- /dev/null +++ b/services/credit-system/client/credit_management/decrease_credit_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// DecreaseCreditReader is a Reader for the DecreaseCredit structure. +type DecreaseCreditReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DecreaseCreditReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDecreaseCreditOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewDecreaseCreditNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewDecreaseCreditInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewDecreaseCreditOK creates a DecreaseCreditOK with default headers values +func NewDecreaseCreditOK() *DecreaseCreditOK { + return &DecreaseCreditOK{} +} + +/*DecreaseCreditOK handles this case with default header values. + +Credit status of the account with the provided id +*/ +type DecreaseCreditOK struct { + Payload *models.CreditStatus +} + +func (o *DecreaseCreditOK) Error() string { + return fmt.Sprintf("[POST /{medium}/available/decrease/{id}][%d] decreaseCreditOK %+v", 200, o.Payload) +} + +func (o *DecreaseCreditOK) GetPayload() *models.CreditStatus { + return o.Payload +} + +func (o *DecreaseCreditOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CreditStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDecreaseCreditNotFound creates a DecreaseCreditNotFound with default headers values +func NewDecreaseCreditNotFound() *DecreaseCreditNotFound { + return &DecreaseCreditNotFound{} +} + +/*DecreaseCreditNotFound handles this case with default header values. + +The account with the id provided doesn't exist +*/ +type DecreaseCreditNotFound struct { + Payload *models.ErrorResponse +} + +func (o *DecreaseCreditNotFound) Error() string { + return fmt.Sprintf("[POST /{medium}/available/decrease/{id}][%d] decreaseCreditNotFound %+v", 404, o.Payload) +} + +func (o *DecreaseCreditNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *DecreaseCreditNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDecreaseCreditInternalServerError creates a DecreaseCreditInternalServerError with default headers values +func NewDecreaseCreditInternalServerError() *DecreaseCreditInternalServerError { + return &DecreaseCreditInternalServerError{} +} + +/*DecreaseCreditInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type DecreaseCreditInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *DecreaseCreditInternalServerError) Error() string { + return fmt.Sprintf("[POST /{medium}/available/decrease/{id}][%d] decreaseCreditInternalServerError %+v", 500, o.Payload) +} + +func (o *DecreaseCreditInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *DecreaseCreditInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/credit_management/get_credit_parameters.go b/services/credit-system/client/credit_management/get_credit_parameters.go new file mode 100644 index 0000000..8131756 --- /dev/null +++ b/services/credit-system/client/credit_management/get_credit_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCreditParams creates a new GetCreditParams object +// with the default values initialized. +func NewGetCreditParams() *GetCreditParams { + var () + return &GetCreditParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetCreditParamsWithTimeout creates a new GetCreditParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetCreditParamsWithTimeout(timeout time.Duration) *GetCreditParams { + var () + return &GetCreditParams{ + + timeout: timeout, + } +} + +// NewGetCreditParamsWithContext creates a new GetCreditParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetCreditParamsWithContext(ctx context.Context) *GetCreditParams { + var () + return &GetCreditParams{ + + Context: ctx, + } +} + +// NewGetCreditParamsWithHTTPClient creates a new GetCreditParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetCreditParamsWithHTTPClient(client *http.Client) *GetCreditParams { + var () + return &GetCreditParams{ + HTTPClient: client, + } +} + +/*GetCreditParams contains all the parameters to send to the API endpoint +for the get credit operation typically these are written to a http.Request +*/ +type GetCreditParams struct { + + /*ID + Id of the account to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get credit params +func (o *GetCreditParams) WithTimeout(timeout time.Duration) *GetCreditParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get credit params +func (o *GetCreditParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get credit params +func (o *GetCreditParams) WithContext(ctx context.Context) *GetCreditParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get credit params +func (o *GetCreditParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get credit params +func (o *GetCreditParams) WithHTTPClient(client *http.Client) *GetCreditParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get credit params +func (o *GetCreditParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get credit params +func (o *GetCreditParams) WithID(id string) *GetCreditParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get credit params +func (o *GetCreditParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCreditParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/credit_management/get_credit_responses.go b/services/credit-system/client/credit_management/get_credit_responses.go new file mode 100644 index 0000000..9473769 --- /dev/null +++ b/services/credit-system/client/credit_management/get_credit_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetCreditReader is a Reader for the GetCredit structure. +type GetCreditReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCreditReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCreditOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetCreditNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetCreditInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetCreditOK creates a GetCreditOK with default headers values +func NewGetCreditOK() *GetCreditOK { + return &GetCreditOK{} +} + +/*GetCreditOK handles this case with default header values. + +Credit status of the account with the provided id +*/ +type GetCreditOK struct { + Payload *models.CreditStatus +} + +func (o *GetCreditOK) Error() string { + return fmt.Sprintf("[GET /account/available/{id}][%d] getCreditOK %+v", 200, o.Payload) +} + +func (o *GetCreditOK) GetPayload() *models.CreditStatus { + return o.Payload +} + +func (o *GetCreditOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CreditStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCreditNotFound creates a GetCreditNotFound with default headers values +func NewGetCreditNotFound() *GetCreditNotFound { + return &GetCreditNotFound{} +} + +/*GetCreditNotFound handles this case with default header values. + +The account with the provided id doesn't exist +*/ +type GetCreditNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetCreditNotFound) Error() string { + return fmt.Sprintf("[GET /account/available/{id}][%d] getCreditNotFound %+v", 404, o.Payload) +} + +func (o *GetCreditNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCreditNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCreditInternalServerError creates a GetCreditInternalServerError with default headers values +func NewGetCreditInternalServerError() *GetCreditInternalServerError { + return &GetCreditInternalServerError{} +} + +/*GetCreditInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetCreditInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetCreditInternalServerError) Error() string { + return fmt.Sprintf("[GET /account/available/{id}][%d] getCreditInternalServerError %+v", 500, o.Payload) +} + +func (o *GetCreditInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCreditInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/credit_management/get_history_parameters.go b/services/credit-system/client/credit_management/get_history_parameters.go new file mode 100644 index 0000000..735a3f5 --- /dev/null +++ b/services/credit-system/client/credit_management/get_history_parameters.go @@ -0,0 +1,200 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetHistoryParams creates a new GetHistoryParams object +// with the default values initialized. +func NewGetHistoryParams() *GetHistoryParams { + var () + return &GetHistoryParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetHistoryParamsWithTimeout creates a new GetHistoryParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetHistoryParamsWithTimeout(timeout time.Duration) *GetHistoryParams { + var () + return &GetHistoryParams{ + + timeout: timeout, + } +} + +// NewGetHistoryParamsWithContext creates a new GetHistoryParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetHistoryParamsWithContext(ctx context.Context) *GetHistoryParams { + var () + return &GetHistoryParams{ + + Context: ctx, + } +} + +// NewGetHistoryParamsWithHTTPClient creates a new GetHistoryParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetHistoryParamsWithHTTPClient(client *http.Client) *GetHistoryParams { + var () + return &GetHistoryParams{ + HTTPClient: client, + } +} + +/*GetHistoryParams contains all the parameters to send to the API endpoint +for the get history operation typically these are written to a http.Request +*/ +type GetHistoryParams struct { + + /*FilterSystem + Boolean variable to control if the system consumptions have to be listed or not + + */ + FilterSystem *bool + /*ID + Id of the account to get the history + + */ + ID string + /*Medium + Medium (cash/credit) to be used as filter + + */ + Medium *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get history params +func (o *GetHistoryParams) WithTimeout(timeout time.Duration) *GetHistoryParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get history params +func (o *GetHistoryParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get history params +func (o *GetHistoryParams) WithContext(ctx context.Context) *GetHistoryParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get history params +func (o *GetHistoryParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get history params +func (o *GetHistoryParams) WithHTTPClient(client *http.Client) *GetHistoryParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get history params +func (o *GetHistoryParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFilterSystem adds the filterSystem to the get history params +func (o *GetHistoryParams) WithFilterSystem(filterSystem *bool) *GetHistoryParams { + o.SetFilterSystem(filterSystem) + return o +} + +// SetFilterSystem adds the filterSystem to the get history params +func (o *GetHistoryParams) SetFilterSystem(filterSystem *bool) { + o.FilterSystem = filterSystem +} + +// WithID adds the id to the get history params +func (o *GetHistoryParams) WithID(id string) *GetHistoryParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get history params +func (o *GetHistoryParams) SetID(id string) { + o.ID = id +} + +// WithMedium adds the medium to the get history params +func (o *GetHistoryParams) WithMedium(medium *string) *GetHistoryParams { + o.SetMedium(medium) + return o +} + +// SetMedium adds the medium to the get history params +func (o *GetHistoryParams) SetMedium(medium *string) { + o.Medium = medium +} + +// WriteToRequest writes these params to a swagger request +func (o *GetHistoryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.FilterSystem != nil { + + // query param filterSystem + var qrFilterSystem bool + if o.FilterSystem != nil { + qrFilterSystem = *o.FilterSystem + } + qFilterSystem := swag.FormatBool(qrFilterSystem) + if qFilterSystem != "" { + if err := r.SetQueryParam("filterSystem", qFilterSystem); err != nil { + return err + } + } + + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Medium != nil { + + // query param medium + var qrMedium string + if o.Medium != nil { + qrMedium = *o.Medium + } + qMedium := qrMedium + if qMedium != "" { + if err := r.SetQueryParam("medium", qMedium); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/credit_management/get_history_responses.go b/services/credit-system/client/credit_management/get_history_responses.go new file mode 100644 index 0000000..2f705e3 --- /dev/null +++ b/services/credit-system/client/credit_management/get_history_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetHistoryReader is a Reader for the GetHistory structure. +type GetHistoryReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetHistoryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetHistoryOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetHistoryNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetHistoryInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetHistoryOK creates a GetHistoryOK with default headers values +func NewGetHistoryOK() *GetHistoryOK { + return &GetHistoryOK{} +} + +/*GetHistoryOK handles this case with default header values. + +Credit status history of the account with the provided id +*/ +type GetHistoryOK struct { + Payload *models.CreditHistory +} + +func (o *GetHistoryOK) Error() string { + return fmt.Sprintf("[GET /history/{id}][%d] getHistoryOK %+v", 200, o.Payload) +} + +func (o *GetHistoryOK) GetPayload() *models.CreditHistory { + return o.Payload +} + +func (o *GetHistoryOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CreditHistory) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetHistoryNotFound creates a GetHistoryNotFound with default headers values +func NewGetHistoryNotFound() *GetHistoryNotFound { + return &GetHistoryNotFound{} +} + +/*GetHistoryNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetHistoryNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetHistoryNotFound) Error() string { + return fmt.Sprintf("[GET /history/{id}][%d] getHistoryNotFound %+v", 404, o.Payload) +} + +func (o *GetHistoryNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetHistoryNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetHistoryInternalServerError creates a GetHistoryInternalServerError with default headers values +func NewGetHistoryInternalServerError() *GetHistoryInternalServerError { + return &GetHistoryInternalServerError{} +} + +/*GetHistoryInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetHistoryInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetHistoryInternalServerError) Error() string { + return fmt.Sprintf("[GET /history/{id}][%d] getHistoryInternalServerError %+v", 500, o.Payload) +} + +func (o *GetHistoryInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetHistoryInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/credit_management/increase_credit_parameters.go b/services/credit-system/client/credit_management/increase_credit_parameters.go new file mode 100644 index 0000000..c27a719 --- /dev/null +++ b/services/credit-system/client/credit_management/increase_credit_parameters.go @@ -0,0 +1,182 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewIncreaseCreditParams creates a new IncreaseCreditParams object +// with the default values initialized. +func NewIncreaseCreditParams() *IncreaseCreditParams { + var () + return &IncreaseCreditParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewIncreaseCreditParamsWithTimeout creates a new IncreaseCreditParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewIncreaseCreditParamsWithTimeout(timeout time.Duration) *IncreaseCreditParams { + var () + return &IncreaseCreditParams{ + + timeout: timeout, + } +} + +// NewIncreaseCreditParamsWithContext creates a new IncreaseCreditParams object +// with the default values initialized, and the ability to set a context for a request +func NewIncreaseCreditParamsWithContext(ctx context.Context) *IncreaseCreditParams { + var () + return &IncreaseCreditParams{ + + Context: ctx, + } +} + +// NewIncreaseCreditParamsWithHTTPClient creates a new IncreaseCreditParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewIncreaseCreditParamsWithHTTPClient(client *http.Client) *IncreaseCreditParams { + var () + return &IncreaseCreditParams{ + HTTPClient: client, + } +} + +/*IncreaseCreditParams contains all the parameters to send to the API endpoint +for the increase credit operation typically these are written to a http.Request +*/ +type IncreaseCreditParams struct { + + /*Amount + Amount to be inccreased + + */ + Amount float64 + /*ID + Id of the account to be checked + + */ + ID string + /*Medium + Medium (cash/credit) to be used in the accounting + + */ + Medium string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the increase credit params +func (o *IncreaseCreditParams) WithTimeout(timeout time.Duration) *IncreaseCreditParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the increase credit params +func (o *IncreaseCreditParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the increase credit params +func (o *IncreaseCreditParams) WithContext(ctx context.Context) *IncreaseCreditParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the increase credit params +func (o *IncreaseCreditParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the increase credit params +func (o *IncreaseCreditParams) WithHTTPClient(client *http.Client) *IncreaseCreditParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the increase credit params +func (o *IncreaseCreditParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAmount adds the amount to the increase credit params +func (o *IncreaseCreditParams) WithAmount(amount float64) *IncreaseCreditParams { + o.SetAmount(amount) + return o +} + +// SetAmount adds the amount to the increase credit params +func (o *IncreaseCreditParams) SetAmount(amount float64) { + o.Amount = amount +} + +// WithID adds the id to the increase credit params +func (o *IncreaseCreditParams) WithID(id string) *IncreaseCreditParams { + o.SetID(id) + return o +} + +// SetID adds the id to the increase credit params +func (o *IncreaseCreditParams) SetID(id string) { + o.ID = id +} + +// WithMedium adds the medium to the increase credit params +func (o *IncreaseCreditParams) WithMedium(medium string) *IncreaseCreditParams { + o.SetMedium(medium) + return o +} + +// SetMedium adds the medium to the increase credit params +func (o *IncreaseCreditParams) SetMedium(medium string) { + o.Medium = medium +} + +// WriteToRequest writes these params to a swagger request +func (o *IncreaseCreditParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param amount + qrAmount := o.Amount + qAmount := swag.FormatFloat64(qrAmount) + if qAmount != "" { + if err := r.SetQueryParam("amount", qAmount); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // path param medium + if err := r.SetPathParam("medium", o.Medium); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/credit_management/increase_credit_responses.go b/services/credit-system/client/credit_management/increase_credit_responses.go new file mode 100644 index 0000000..4e38978 --- /dev/null +++ b/services/credit-system/client/credit_management/increase_credit_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// IncreaseCreditReader is a Reader for the IncreaseCredit structure. +type IncreaseCreditReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *IncreaseCreditReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewIncreaseCreditOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewIncreaseCreditNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewIncreaseCreditInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewIncreaseCreditOK creates a IncreaseCreditOK with default headers values +func NewIncreaseCreditOK() *IncreaseCreditOK { + return &IncreaseCreditOK{} +} + +/*IncreaseCreditOK handles this case with default header values. + +Credit status of the account with the provided id +*/ +type IncreaseCreditOK struct { + Payload *models.CreditStatus +} + +func (o *IncreaseCreditOK) Error() string { + return fmt.Sprintf("[POST /{medium}/available/increase/{id}][%d] increaseCreditOK %+v", 200, o.Payload) +} + +func (o *IncreaseCreditOK) GetPayload() *models.CreditStatus { + return o.Payload +} + +func (o *IncreaseCreditOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CreditStatus) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewIncreaseCreditNotFound creates a IncreaseCreditNotFound with default headers values +func NewIncreaseCreditNotFound() *IncreaseCreditNotFound { + return &IncreaseCreditNotFound{} +} + +/*IncreaseCreditNotFound handles this case with default header values. + +The account with the id provided doesn't exist +*/ +type IncreaseCreditNotFound struct { + Payload *models.ErrorResponse +} + +func (o *IncreaseCreditNotFound) Error() string { + return fmt.Sprintf("[POST /{medium}/available/increase/{id}][%d] increaseCreditNotFound %+v", 404, o.Payload) +} + +func (o *IncreaseCreditNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *IncreaseCreditNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewIncreaseCreditInternalServerError creates a IncreaseCreditInternalServerError with default headers values +func NewIncreaseCreditInternalServerError() *IncreaseCreditInternalServerError { + return &IncreaseCreditInternalServerError{} +} + +/*IncreaseCreditInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type IncreaseCreditInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *IncreaseCreditInternalServerError) Error() string { + return fmt.Sprintf("[POST /{medium}/available/increase/{id}][%d] increaseCreditInternalServerError %+v", 500, o.Payload) +} + +func (o *IncreaseCreditInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *IncreaseCreditInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/credit_manager_management_api_client.go b/services/credit-system/client/credit_manager_management_api_client.go new file mode 100644 index 0000000..ed946eb --- /dev/null +++ b/services/credit-system/client/credit_manager_management_api_client.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client/account_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client/credit_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/client/trigger_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v1.0" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new credit manager management API HTTP client. +func New(c Config) *CreditManagerManagementAPI { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(CreditManagerManagementAPI) + cli.Transport = transport + cli.AccountManagement = account_management.New(transport, strfmt.Default, c.AuthInfo) + cli.CreditManagement = credit_management.New(transport, strfmt.Default, c.AuthInfo) + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// CreditManagerManagementAPI is a client for credit manager management API +type CreditManagerManagementAPI struct { + AccountManagement *account_management.Client + CreditManagement *credit_management.Client + StatusManagement *status_management.Client + TriggerManagement *trigger_management.Client + Transport runtime.ClientTransport +} diff --git a/services/credit-system/client/status_management/get_status_parameters.go b/services/credit-system/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..bc38256 --- /dev/null +++ b/services/credit-system/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the endpoint to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/status_management/get_status_responses.go b/services/credit-system/client/status_management/get_status_responses.go new file mode 100644 index 0000000..20d82ea --- /dev/null +++ b/services/credit-system/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/status_management/show_status_parameters.go b/services/credit-system/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/services/credit-system/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/status_management/show_status_responses.go b/services/credit-system/client/status_management/show_status_responses.go new file mode 100644 index 0000000..ea3b5fa --- /dev/null +++ b/services/credit-system/client/status_management/show_status_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/status_management/status_management_client.go b/services/credit-system/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/services/credit-system/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/services/credit-system/client/trigger_management/exec_sample_parameters.go b/services/credit-system/client/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..2e1428d --- /dev/null +++ b/services/credit-system/client/trigger_management/exec_sample_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// with the default values initialized. +func NewExecSampleParams() *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewExecSampleParamsWithTimeout creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewExecSampleParamsWithTimeout(timeout time.Duration) *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: timeout, + } +} + +// NewExecSampleParamsWithContext creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a context for a request +func NewExecSampleParamsWithContext(ctx context.Context) *ExecSampleParams { + + return &ExecSampleParams{ + + Context: ctx, + } +} + +// NewExecSampleParamsWithHTTPClient creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewExecSampleParamsWithHTTPClient(client *http.Client) *ExecSampleParams { + + return &ExecSampleParams{ + HTTPClient: client, + } +} + +/*ExecSampleParams contains all the parameters to send to the API endpoint +for the exec sample operation typically these are written to a http.Request +*/ +type ExecSampleParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) WithTimeout(timeout time.Duration) *ExecSampleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the exec sample params +func (o *ExecSampleParams) WithContext(ctx context.Context) *ExecSampleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the exec sample params +func (o *ExecSampleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) WithHTTPClient(client *http.Client) *ExecSampleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ExecSampleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/client/trigger_management/exec_sample_responses.go b/services/credit-system/client/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..40e272a --- /dev/null +++ b/services/credit-system/client/trigger_management/exec_sample_responses.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// ExecSampleReader is a Reader for the ExecSample structure. +type ExecSampleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ExecSampleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewExecSampleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewExecSampleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewExecSampleOK creates a ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + return &ExecSampleOK{} +} + +/*ExecSampleOK handles this case with default header values. + +Sample task executed successfully +*/ +type ExecSampleOK struct { +} + +func (o *ExecSampleOK) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleOK ", 200) +} + +func (o *ExecSampleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewExecSampleInternalServerError creates a ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + return &ExecSampleInternalServerError{} +} + +/*ExecSampleInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ExecSampleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ExecSampleInternalServerError) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleInternalServerError %+v", 500, o.Payload) +} + +func (o *ExecSampleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ExecSampleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/credit-system/client/trigger_management/trigger_management_client.go b/services/credit-system/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..b8010e0 --- /dev/null +++ b/services/credit-system/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + ExecSample samples task trigger*/ + ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +ExecSample samples task trigger +*/ +func (a *Client) ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "execSample", + Method: "GET", + PathPattern: "/trigger/sample", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ExecSampleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ExecSampleOK), nil + +} diff --git a/services/credit-system/go.mod b/services/credit-system/go.mod new file mode 100644 index 0000000..9f3f1b2 --- /dev/null +++ b/services/credit-system/go.mod @@ -0,0 +1,44 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system + +go 1.15 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/gin-gonic/gin v1.5.0 // indirect + github.com/go-openapi/analysis v0.21.1 // indirect + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/go-resty/resty/v2 v2.7.0 // indirect + github.com/go-stack/stack v1.8.1 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/jackc/pgx/v4 v4.14.1 // indirect + github.com/jinzhu/now v1.1.4 // indirect + github.com/klauspost/cpuid/v2 v2.0.9 // indirect + github.com/pierrec/lz4 v2.6.1+incompatible // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/remeh/sizedwaitgroup v1.0.0 + github.com/rs/cors v1.8.2 + github.com/segmentio/asm v1.1.3 // indirect + github.com/segmentio/encoding v0.3.2 + github.com/segmentio/kafka-go v0.4.25 + github.com/segmentio/ksuid v1.0.4 // indirect + github.com/spf13/viper v1.10.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + go.mongodb.org/mongo-driver v1.8.1 // indirect + golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect + golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect + golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/services/credit-system/models/account_status.go b/services/credit-system/models/account_status.go new file mode 100644 index 0000000..ac9a21d --- /dev/null +++ b/services/credit-system/models/account_status.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// AccountStatus account status +// +// swagger:model AccountStatus +type AccountStatus struct { + + // account ID + AccountID string `json:"AccountID,omitempty" gorm:"primary_key"` + + // created at + // Format: datetime + CreatedAt strfmt.DateTime `json:"CreatedAt,omitempty" gorm:"type:timestamptz"` + + // enabled + // Required: true + Enabled bool `json:"Enabled" gorm:"default:true"` +} + +// Validate validates this account status +func (m *AccountStatus) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCreatedAt(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEnabled(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *AccountStatus) validateCreatedAt(formats strfmt.Registry) error { + + if swag.IsZero(m.CreatedAt) { // not required + return nil + } + + if err := validate.FormatOf("CreatedAt", "body", "datetime", m.CreatedAt.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *AccountStatus) validateEnabled(formats strfmt.Registry) error { + + if err := validate.Required("Enabled", "body", bool(m.Enabled)); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *AccountStatus) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *AccountStatus) UnmarshalBinary(b []byte) error { + var res AccountStatus + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/credit-system/models/credit_events.go b/services/credit-system/models/credit_events.go new file mode 100644 index 0000000..8308b1c --- /dev/null +++ b/services/credit-system/models/credit_events.go @@ -0,0 +1,193 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreditEvents credit events +// +// swagger:model CreditEvents +type CreditEvents struct { + + // account Id + AccountID string `json:"AccountId,omitempty" gorm:"index"` + + // authorized by + AuthorizedBy string `json:"AuthorizedBy,omitempty"` + + // delta + Delta float64 `json:"Delta,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // event type + // Enum: [AuthorizedIncrease AuthorizedDecrease Consumption AutomaticCreditExpiry Refund] + EventType *string `json:"EventType,omitempty" gorm:"index;default:Consumption"` + + // ID + ID int64 `json:"ID,omitempty" gorm:"primary_key"` + + // medium + // Enum: [CREDIT CASH] + Medium *string `json:"Medium,omitempty" gorm:"index;default:CREDIT"` + + // timestamp + // Format: datetime + Timestamp strfmt.DateTime `json:"Timestamp,omitempty" gorm:"type:timestamptz"` +} + +// Validate validates this credit events +func (m *CreditEvents) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMedium(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimestamp(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var creditEventsTypeEventTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["AuthorizedIncrease","AuthorizedDecrease","Consumption","AutomaticCreditExpiry","Refund"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + creditEventsTypeEventTypePropEnum = append(creditEventsTypeEventTypePropEnum, v) + } +} + +const ( + + // CreditEventsEventTypeAuthorizedIncrease captures enum value "AuthorizedIncrease" + CreditEventsEventTypeAuthorizedIncrease string = "AuthorizedIncrease" + + // CreditEventsEventTypeAuthorizedDecrease captures enum value "AuthorizedDecrease" + CreditEventsEventTypeAuthorizedDecrease string = "AuthorizedDecrease" + + // CreditEventsEventTypeConsumption captures enum value "Consumption" + CreditEventsEventTypeConsumption string = "Consumption" + + // CreditEventsEventTypeAutomaticCreditExpiry captures enum value "AutomaticCreditExpiry" + CreditEventsEventTypeAutomaticCreditExpiry string = "AutomaticCreditExpiry" + + // CreditEventsEventTypeRefund captures enum value "Refund" + CreditEventsEventTypeRefund string = "Refund" +) + +// prop value enum +func (m *CreditEvents) validateEventTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, creditEventsTypeEventTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *CreditEvents) validateEventType(formats strfmt.Registry) error { + + if swag.IsZero(m.EventType) { // not required + return nil + } + + // value enum + if err := m.validateEventTypeEnum("EventType", "body", *m.EventType); err != nil { + return err + } + + return nil +} + +var creditEventsTypeMediumPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CREDIT","CASH"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + creditEventsTypeMediumPropEnum = append(creditEventsTypeMediumPropEnum, v) + } +} + +const ( + + // CreditEventsMediumCREDIT captures enum value "CREDIT" + CreditEventsMediumCREDIT string = "CREDIT" + + // CreditEventsMediumCASH captures enum value "CASH" + CreditEventsMediumCASH string = "CASH" +) + +// prop value enum +func (m *CreditEvents) validateMediumEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, creditEventsTypeMediumPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *CreditEvents) validateMedium(formats strfmt.Registry) error { + + if swag.IsZero(m.Medium) { // not required + return nil + } + + // value enum + if err := m.validateMediumEnum("Medium", "body", *m.Medium); err != nil { + return err + } + + return nil +} + +func (m *CreditEvents) validateTimestamp(formats strfmt.Registry) error { + + if swag.IsZero(m.Timestamp) { // not required + return nil + } + + if err := validate.FormatOf("Timestamp", "body", "datetime", m.Timestamp.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreditEvents) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreditEvents) UnmarshalBinary(b []byte) error { + var res CreditEvents + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/credit-system/models/credit_history.go b/services/credit-system/models/credit_history.go new file mode 100644 index 0000000..872cc0f --- /dev/null +++ b/services/credit-system/models/credit_history.go @@ -0,0 +1,83 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CreditHistory credit history +// +// swagger:model CreditHistory +type CreditHistory struct { + + // account ID + AccountID string `json:"AccountID,omitempty" gorm:"primary_key"` + + // events + Events []*Event `json:"Events"` +} + +// Validate validates this credit history +func (m *CreditHistory) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEvents(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreditHistory) validateEvents(formats strfmt.Registry) error { + + if swag.IsZero(m.Events) { // not required + return nil + } + + for i := 0; i < len(m.Events); i++ { + if swag.IsZero(m.Events[i]) { // not required + continue + } + + if m.Events[i] != nil { + if err := m.Events[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("Events" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreditHistory) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreditHistory) UnmarshalBinary(b []byte) error { + var res CreditHistory + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/credit-system/models/credit_status.go b/services/credit-system/models/credit_status.go new file mode 100644 index 0000000..9a35853 --- /dev/null +++ b/services/credit-system/models/credit_status.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CreditStatus credit status +// +// swagger:model CreditStatus +type CreditStatus struct { + + // account ID + AccountID string `json:"AccountID,omitempty" gorm:"primary_key"` + + // available cash + AvailableCash float64 `json:"AvailableCash,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // available credit + AvailableCredit float64 `json:"AvailableCredit,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // last update + // Format: datetime + LastUpdate strfmt.DateTime `json:"LastUpdate,omitempty" gorm:"type:timestamptz"` +} + +// Validate validates this credit status +func (m *CreditStatus) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateLastUpdate(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CreditStatus) validateLastUpdate(formats strfmt.Registry) error { + + if swag.IsZero(m.LastUpdate) { // not required + return nil + } + + if err := validate.FormatOf("LastUpdate", "body", "datetime", m.LastUpdate.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CreditStatus) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CreditStatus) UnmarshalBinary(b []byte) error { + var res CreditStatus + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/credit-system/models/error_response.go b/services/credit-system/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/services/credit-system/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/credit-system/models/event.go b/services/credit-system/models/event.go new file mode 100644 index 0000000..b1a83df --- /dev/null +++ b/services/credit-system/models/event.go @@ -0,0 +1,187 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Event event +// +// swagger:model Event +type Event struct { + + // authorized by + AuthorizedBy string `json:"AuthorizedBy,omitempty"` + + // delta + Delta float64 `json:"Delta,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // event type + // Enum: [AuthorizedIncrease AuthorizedDecrease Consumption AutomaticCreditExpiry Refund] + EventType *string `json:"EventType,omitempty" gorm:"index;default:Consumption"` + + // medium + // Enum: [CREDIT CASH] + Medium *string `json:"Medium,omitempty" gorm:"index;default:CREDIT"` + + // timestamp + // Format: datetime + Timestamp strfmt.DateTime `json:"Timestamp,omitempty" gorm:"type:timestamptz"` +} + +// Validate validates this event +func (m *Event) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMedium(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimestamp(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var eventTypeEventTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["AuthorizedIncrease","AuthorizedDecrease","Consumption","AutomaticCreditExpiry","Refund"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + eventTypeEventTypePropEnum = append(eventTypeEventTypePropEnum, v) + } +} + +const ( + + // EventEventTypeAuthorizedIncrease captures enum value "AuthorizedIncrease" + EventEventTypeAuthorizedIncrease string = "AuthorizedIncrease" + + // EventEventTypeAuthorizedDecrease captures enum value "AuthorizedDecrease" + EventEventTypeAuthorizedDecrease string = "AuthorizedDecrease" + + // EventEventTypeConsumption captures enum value "Consumption" + EventEventTypeConsumption string = "Consumption" + + // EventEventTypeAutomaticCreditExpiry captures enum value "AutomaticCreditExpiry" + EventEventTypeAutomaticCreditExpiry string = "AutomaticCreditExpiry" + + // EventEventTypeRefund captures enum value "Refund" + EventEventTypeRefund string = "Refund" +) + +// prop value enum +func (m *Event) validateEventTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, eventTypeEventTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Event) validateEventType(formats strfmt.Registry) error { + + if swag.IsZero(m.EventType) { // not required + return nil + } + + // value enum + if err := m.validateEventTypeEnum("EventType", "body", *m.EventType); err != nil { + return err + } + + return nil +} + +var eventTypeMediumPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CREDIT","CASH"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + eventTypeMediumPropEnum = append(eventTypeMediumPropEnum, v) + } +} + +const ( + + // EventMediumCREDIT captures enum value "CREDIT" + EventMediumCREDIT string = "CREDIT" + + // EventMediumCASH captures enum value "CASH" + EventMediumCASH string = "CASH" +) + +// prop value enum +func (m *Event) validateMediumEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, eventTypeMediumPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Event) validateMedium(formats strfmt.Registry) error { + + if swag.IsZero(m.Medium) { // not required + return nil + } + + // value enum + if err := m.validateMediumEnum("Medium", "body", *m.Medium); err != nil { + return err + } + + return nil +} + +func (m *Event) validateTimestamp(formats strfmt.Registry) error { + + if swag.IsZero(m.Timestamp) { // not required + return nil + } + + if err := validate.FormatOf("Timestamp", "body", "datetime", m.Timestamp.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Event) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Event) UnmarshalBinary(b []byte) error { + var res Event + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/credit-system/models/status.go b/services/credit-system/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/services/credit-system/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/credit-system/restapi/configure_credit_manager_management_api.go b/services/credit-system/restapi/configure_credit_manager_management_api.go new file mode 100644 index 0000000..1c12fae --- /dev/null +++ b/services/credit-system/restapi/configure_credit_manager_management_api.go @@ -0,0 +1,259 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/account_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/credit_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/trigger_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name AccountManagementAPI -inpkg + +/* AccountManagementAPI */ +type AccountManagementAPI interface { + /* CreateAccount Creates a new account in the system */ + CreateAccount(ctx context.Context, params account_management.CreateAccountParams) middleware.Responder + + /* DisableAccount Disables the account with the id provided in the system */ + DisableAccount(ctx context.Context, params account_management.DisableAccountParams) middleware.Responder + + /* EnableAccount Enables the account with the id provided in the system */ + EnableAccount(ctx context.Context, params account_management.EnableAccountParams) middleware.Responder + + /* GetAccountStatus Basic status of the account with the id provided in the system */ + GetAccountStatus(ctx context.Context, params account_management.GetAccountStatusParams) middleware.Responder + + /* ListAccounts List of the accounts in the system */ + ListAccounts(ctx context.Context, params account_management.ListAccountsParams) middleware.Responder +} + +//go:generate mockery -name CreditManagementAPI -inpkg + +/* CreditManagementAPI */ +type CreditManagementAPI interface { + /* AddConsumption Adds a consumption to the system */ + AddConsumption(ctx context.Context, params credit_management.AddConsumptionParams) middleware.Responder + + /* DecreaseCredit Insert a new reseller in the system. */ + DecreaseCredit(ctx context.Context, params credit_management.DecreaseCreditParams) middleware.Responder + + /* GetCredit Credit status of the account with the provided id */ + GetCredit(ctx context.Context, params credit_management.GetCreditParams) middleware.Responder + + /* GetHistory Credit history of the customer with id */ + GetHistory(ctx context.Context, params credit_management.GetHistoryParams) middleware.Responder + + /* IncreaseCredit Insert a new reseller in the system. */ + IncreaseCredit(ctx context.Context, params credit_management.IncreaseCreditParams) middleware.Responder +} + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* ExecSample Sample task trigger */ + ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + AccountManagementAPI + CreditManagementAPI + StatusManagementAPI + TriggerManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) + // Authenticator to use for all APIKey authentication + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // Authenticator to use for all Bearer authentication + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // Authenticator to use for all Basic authentication + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *CreditManagerManagementAPI instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.CreditManagerManagementAPIAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewCreditManagerManagementAPIAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + if c.APIKeyAuthenticator != nil { + api.APIKeyAuthenticator = c.APIKeyAuthenticator + } + if c.BasicAuthenticator != nil { + api.BasicAuthenticator = c.BasicAuthenticator + } + if c.BearerAuthenticator != nil { + api.BearerAuthenticator = c.BearerAuthenticator + } + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.CreditManagementAddConsumptionHandler = credit_management.AddConsumptionHandlerFunc(func(params credit_management.AddConsumptionParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CreditManagementAPI.AddConsumption(ctx, params) + }) + api.AccountManagementCreateAccountHandler = account_management.CreateAccountHandlerFunc(func(params account_management.CreateAccountParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.AccountManagementAPI.CreateAccount(ctx, params) + }) + api.CreditManagementDecreaseCreditHandler = credit_management.DecreaseCreditHandlerFunc(func(params credit_management.DecreaseCreditParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CreditManagementAPI.DecreaseCredit(ctx, params) + }) + api.AccountManagementDisableAccountHandler = account_management.DisableAccountHandlerFunc(func(params account_management.DisableAccountParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.AccountManagementAPI.DisableAccount(ctx, params) + }) + api.AccountManagementEnableAccountHandler = account_management.EnableAccountHandlerFunc(func(params account_management.EnableAccountParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.AccountManagementAPI.EnableAccount(ctx, params) + }) + api.TriggerManagementExecSampleHandler = trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.ExecSample(ctx, params) + }) + api.AccountManagementGetAccountStatusHandler = account_management.GetAccountStatusHandlerFunc(func(params account_management.GetAccountStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.AccountManagementAPI.GetAccountStatus(ctx, params) + }) + api.CreditManagementGetCreditHandler = credit_management.GetCreditHandlerFunc(func(params credit_management.GetCreditParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CreditManagementAPI.GetCredit(ctx, params) + }) + api.CreditManagementGetHistoryHandler = credit_management.GetHistoryHandlerFunc(func(params credit_management.GetHistoryParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CreditManagementAPI.GetHistory(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.CreditManagementIncreaseCreditHandler = credit_management.IncreaseCreditHandlerFunc(func(params credit_management.IncreaseCreditParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CreditManagementAPI.IncreaseCredit(ctx, params) + }) + api.AccountManagementListAccountsHandler = account_management.ListAccountsHandlerFunc(func(params account_management.ListAccountsParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.AccountManagementAPI.ListAccounts(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/services/credit-system/restapi/doc.go b/services/credit-system/restapi/doc.go new file mode 100644 index 0000000..28da4c6 --- /dev/null +++ b/services/credit-system/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi Credit Manager Management API +// +// An API which supports creation, deletion, listing etc of Credit Manager +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v1.0 +// Version: 1.0.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/services/credit-system/restapi/embedded_spec.go b/services/credit-system/restapi/embedded_spec.go new file mode 100644 index 0000000..2c15827 --- /dev/null +++ b/services/credit-system/restapi/embedded_spec.go @@ -0,0 +1,2036 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Credit Manager", + "title": "Credit Manager Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/account/available/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Credit status of the account with the provided id", + "operationId": "getCredit", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the provided id doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/create/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Creates a new account in the system", + "operationId": "createAccount", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be created", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Account created, provided information of the new item created", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "409": { + "description": "The account with the id provided already exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/disable/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Disables the account with the id provided in the system", + "operationId": "disableAccount", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be disabled", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the account with provided id in the system after the operation succeded", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/enable/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Enables the account with the id provided in the system", + "operationId": "enableAccount", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be enabled", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the account with provided id in the system after the operation succeded", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/list": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "List of the accounts in the system", + "operationId": "listAccounts", + "responses": { + "200": { + "description": "List of accounts in the system", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/AccountStatus" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Basic status of the account with the id provided in the system", + "operationId": "getAccountStatus", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the account with provided id in the system", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/history/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Credit history of the customer with id", + "operationId": "getHistory", + "parameters": [ + { + "type": "string", + "description": "Id of the account to get the history", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "boolean", + "description": "Boolean variable to control if the system consumptions have to be listed or not", + "name": "filterSystem", + "in": "query" + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used as filter", + "name": "medium", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Credit status history of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditHistory" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "account", + "credit" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/{medium}/available/decrease/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Insert a new reseller in the system.", + "operationId": "decreaseCredit", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "number", + "format": "double", + "description": "Amount to be decreased", + "name": "amount", + "in": "query", + "required": true + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used in the accounting", + "name": "medium", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/{medium}/available/increase/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Insert a new reseller in the system.", + "operationId": "increaseCredit", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "number", + "format": "double", + "description": "Amount to be inccreased", + "name": "amount", + "in": "query", + "required": true + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used in the accounting", + "name": "medium", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/{medium}/consume/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Adds a consumption to the system", + "operationId": "addConsumption", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "number", + "format": "double", + "description": "Amount to be decreased", + "name": "amount", + "in": "query", + "required": true + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used in the accounting", + "name": "medium", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "AccountStatus": { + "type": "object", + "required": [ + "Enabled" + ], + "properties": { + "AccountID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "CreatedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + }, + "Enabled": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + } + } + }, + "CreditEvents": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "AuthorizedBy": { + "type": "string" + }, + "Delta": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EventType": { + "type": "string", + "default": "Consumption", + "enum": [ + "AuthorizedIncrease", + "AuthorizedDecrease", + "Consumption", + "AutomaticCreditExpiry", + "Refund" + ], + "x-go-custom-tag": "gorm:\"index;default:Consumption\"" + }, + "ID": { + "type": "integer", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "Medium": { + "type": "string", + "default": "CREDIT", + "enum": [ + "CREDIT", + "CASH" + ], + "x-go-custom-tag": "gorm:\"index;default:CREDIT\"" + }, + "Timestamp": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + } + } + }, + "CreditHistory": { + "type": "object", + "properties": { + "AccountID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "Events": { + "type": "array", + "items": { + "$ref": "#/definitions/Event" + } + } + } + }, + "CreditStatus": { + "type": "object", + "properties": { + "AccountID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "AvailableCash": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "AvailableCredit": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "LastUpdate": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Event": { + "type": "object", + "properties": { + "AuthorizedBy": { + "type": "string" + }, + "Delta": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EventType": { + "type": "string", + "default": "Consumption", + "enum": [ + "AuthorizedIncrease", + "AuthorizedDecrease", + "Consumption", + "AutomaticCreditExpiry", + "Refund" + ], + "x-go-custom-tag": "gorm:\"index;default:Consumption\"" + }, + "Medium": { + "type": "string", + "default": "CREDIT", + "enum": [ + "CREDIT", + "CASH" + ], + "x-go-custom-tag": "gorm:\"index;default:CREDIT\"" + }, + "Timestamp": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the control of the credits per account", + "name": "creditManagement" + }, + { + "description": "Actions relating to the account management in the service", + "name": "accountManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Credit Manager", + "title": "Credit Manager Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/account/available/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Credit status of the account with the provided id", + "operationId": "getCredit", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the provided id doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/create/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Creates a new account in the system", + "operationId": "createAccount", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be created", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "201": { + "description": "Account created, provided information of the new item created", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "409": { + "description": "The account with the id provided already exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/disable/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Disables the account with the id provided in the system", + "operationId": "disableAccount", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be disabled", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the account with provided id in the system after the operation succeded", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/enable/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Enables the account with the id provided in the system", + "operationId": "enableAccount", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be enabled", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the account with provided id in the system after the operation succeded", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/list": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "List of the accounts in the system", + "operationId": "listAccounts", + "responses": { + "200": { + "description": "List of accounts in the system", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/AccountStatus" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/account/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "accountManagement" + ], + "summary": "Basic status of the account with the id provided in the system", + "operationId": "getAccountStatus", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the account with provided id in the system", + "schema": { + "$ref": "#/definitions/AccountStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/history/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Credit history of the customer with id", + "operationId": "getHistory", + "parameters": [ + { + "type": "string", + "description": "Id of the account to get the history", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "boolean", + "description": "Boolean variable to control if the system consumptions have to be listed or not", + "name": "filterSystem", + "in": "query" + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used as filter", + "name": "medium", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Credit status history of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditHistory" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "account", + "credit" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/{medium}/available/decrease/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Insert a new reseller in the system.", + "operationId": "decreaseCredit", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "number", + "format": "double", + "description": "Amount to be decreased", + "name": "amount", + "in": "query", + "required": true + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used in the accounting", + "name": "medium", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/{medium}/available/increase/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Insert a new reseller in the system.", + "operationId": "increaseCredit", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "number", + "format": "double", + "description": "Amount to be inccreased", + "name": "amount", + "in": "query", + "required": true + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used in the accounting", + "name": "medium", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/{medium}/consume/{id}": { + "post": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "creditManagement" + ], + "summary": "Adds a consumption to the system", + "operationId": "addConsumption", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "number", + "format": "double", + "description": "Amount to be decreased", + "name": "amount", + "in": "query", + "required": true + }, + { + "enum": [ + "credit", + "cash" + ], + "type": "string", + "description": "Medium (cash/credit) to be used in the accounting", + "name": "medium", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Credit status of the account with the provided id", + "schema": { + "$ref": "#/definitions/CreditStatus" + } + }, + "404": { + "description": "The account with the id provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "AccountStatus": { + "type": "object", + "required": [ + "Enabled" + ], + "properties": { + "AccountID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "CreatedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + }, + "Enabled": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + } + } + }, + "CreditEvents": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "AuthorizedBy": { + "type": "string" + }, + "Delta": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EventType": { + "type": "string", + "default": "Consumption", + "enum": [ + "AuthorizedIncrease", + "AuthorizedDecrease", + "Consumption", + "AutomaticCreditExpiry", + "Refund" + ], + "x-go-custom-tag": "gorm:\"index;default:Consumption\"" + }, + "ID": { + "type": "integer", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "Medium": { + "type": "string", + "default": "CREDIT", + "enum": [ + "CREDIT", + "CASH" + ], + "x-go-custom-tag": "gorm:\"index;default:CREDIT\"" + }, + "Timestamp": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + } + } + }, + "CreditHistory": { + "type": "object", + "properties": { + "AccountID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "Events": { + "type": "array", + "items": { + "$ref": "#/definitions/Event" + } + } + } + }, + "CreditStatus": { + "type": "object", + "properties": { + "AccountID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + }, + "AvailableCash": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "AvailableCredit": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "LastUpdate": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Event": { + "type": "object", + "properties": { + "AuthorizedBy": { + "type": "string" + }, + "Delta": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EventType": { + "type": "string", + "default": "Consumption", + "enum": [ + "AuthorizedIncrease", + "AuthorizedDecrease", + "Consumption", + "AutomaticCreditExpiry", + "Refund" + ], + "x-go-custom-tag": "gorm:\"index;default:Consumption\"" + }, + "Medium": { + "type": "string", + "default": "CREDIT", + "enum": [ + "CREDIT", + "CASH" + ], + "x-go-custom-tag": "gorm:\"index;default:CREDIT\"" + }, + "Timestamp": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the control of the credits per account", + "name": "creditManagement" + }, + { + "description": "Actions relating to the account management in the service", + "name": "accountManagement" + } + ] +}`)) +} diff --git a/services/credit-system/restapi/operations/account_management/create_account.go b/services/credit-system/restapi/operations/account_management/create_account.go new file mode 100644 index 0000000..87bbf88 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/create_account.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// CreateAccountHandlerFunc turns a function with the right signature into a create account handler +type CreateAccountHandlerFunc func(CreateAccountParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn CreateAccountHandlerFunc) Handle(params CreateAccountParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// CreateAccountHandler interface for that can handle valid create account params +type CreateAccountHandler interface { + Handle(CreateAccountParams, interface{}) middleware.Responder +} + +// NewCreateAccount creates a new http.Handler for the create account operation +func NewCreateAccount(ctx *middleware.Context, handler CreateAccountHandler) *CreateAccount { + return &CreateAccount{Context: ctx, Handler: handler} +} + +/*CreateAccount swagger:route GET /account/create/{id} accountManagement createAccount + +Creates a new account in the system + +*/ +type CreateAccount struct { + Context *middleware.Context + Handler CreateAccountHandler +} + +func (o *CreateAccount) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewCreateAccountParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/account_management/create_account_parameters.go b/services/credit-system/restapi/operations/account_management/create_account_parameters.go new file mode 100644 index 0000000..a504922 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/create_account_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewCreateAccountParams creates a new CreateAccountParams object +// no default values defined in spec. +func NewCreateAccountParams() CreateAccountParams { + + return CreateAccountParams{} +} + +// CreateAccountParams contains all the bound params for the create account operation +// typically these are obtained from a http.Request +// +// swagger:parameters createAccount +type CreateAccountParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be created + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewCreateAccountParams() beforehand. +func (o *CreateAccountParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *CreateAccountParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/credit-system/restapi/operations/account_management/create_account_responses.go b/services/credit-system/restapi/operations/account_management/create_account_responses.go new file mode 100644 index 0000000..3906610 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/create_account_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// CreateAccountCreatedCode is the HTTP code returned for type CreateAccountCreated +const CreateAccountCreatedCode int = 201 + +/*CreateAccountCreated Account created, provided information of the new item created + +swagger:response createAccountCreated +*/ +type CreateAccountCreated struct { + + /* + In: Body + */ + Payload *models.AccountStatus `json:"body,omitempty"` +} + +// NewCreateAccountCreated creates CreateAccountCreated with default headers values +func NewCreateAccountCreated() *CreateAccountCreated { + + return &CreateAccountCreated{} +} + +// WithPayload adds the payload to the create account created response +func (o *CreateAccountCreated) WithPayload(payload *models.AccountStatus) *CreateAccountCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create account created response +func (o *CreateAccountCreated) SetPayload(payload *models.AccountStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateAccountCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateAccountConflictCode is the HTTP code returned for type CreateAccountConflict +const CreateAccountConflictCode int = 409 + +/*CreateAccountConflict The account with the id provided already exist + +swagger:response createAccountConflict +*/ +type CreateAccountConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateAccountConflict creates CreateAccountConflict with default headers values +func NewCreateAccountConflict() *CreateAccountConflict { + + return &CreateAccountConflict{} +} + +// WithPayload adds the payload to the create account conflict response +func (o *CreateAccountConflict) WithPayload(payload *models.ErrorResponse) *CreateAccountConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create account conflict response +func (o *CreateAccountConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateAccountConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateAccountInternalServerErrorCode is the HTTP code returned for type CreateAccountInternalServerError +const CreateAccountInternalServerErrorCode int = 500 + +/*CreateAccountInternalServerError Something unexpected happend, error raised + +swagger:response createAccountInternalServerError +*/ +type CreateAccountInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateAccountInternalServerError creates CreateAccountInternalServerError with default headers values +func NewCreateAccountInternalServerError() *CreateAccountInternalServerError { + + return &CreateAccountInternalServerError{} +} + +// WithPayload adds the payload to the create account internal server error response +func (o *CreateAccountInternalServerError) WithPayload(payload *models.ErrorResponse) *CreateAccountInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create account internal server error response +func (o *CreateAccountInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateAccountInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/account_management/create_account_urlbuilder.go b/services/credit-system/restapi/operations/account_management/create_account_urlbuilder.go new file mode 100644 index 0000000..0536797 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/create_account_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// CreateAccountURL generates an URL for the create account operation +type CreateAccountURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateAccountURL) WithBasePath(bp string) *CreateAccountURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateAccountURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *CreateAccountURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/account/create/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on CreateAccountURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *CreateAccountURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *CreateAccountURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *CreateAccountURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on CreateAccountURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on CreateAccountURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *CreateAccountURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/account_management/disable_account.go b/services/credit-system/restapi/operations/account_management/disable_account.go new file mode 100644 index 0000000..04e123e --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/disable_account.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// DisableAccountHandlerFunc turns a function with the right signature into a disable account handler +type DisableAccountHandlerFunc func(DisableAccountParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn DisableAccountHandlerFunc) Handle(params DisableAccountParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// DisableAccountHandler interface for that can handle valid disable account params +type DisableAccountHandler interface { + Handle(DisableAccountParams, interface{}) middleware.Responder +} + +// NewDisableAccount creates a new http.Handler for the disable account operation +func NewDisableAccount(ctx *middleware.Context, handler DisableAccountHandler) *DisableAccount { + return &DisableAccount{Context: ctx, Handler: handler} +} + +/*DisableAccount swagger:route POST /account/disable/{id} accountManagement disableAccount + +Disables the account with the id provided in the system + +*/ +type DisableAccount struct { + Context *middleware.Context + Handler DisableAccountHandler +} + +func (o *DisableAccount) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewDisableAccountParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/account_management/disable_account_parameters.go b/services/credit-system/restapi/operations/account_management/disable_account_parameters.go new file mode 100644 index 0000000..218c9cd --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/disable_account_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewDisableAccountParams creates a new DisableAccountParams object +// no default values defined in spec. +func NewDisableAccountParams() DisableAccountParams { + + return DisableAccountParams{} +} + +// DisableAccountParams contains all the bound params for the disable account operation +// typically these are obtained from a http.Request +// +// swagger:parameters disableAccount +type DisableAccountParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be disabled + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewDisableAccountParams() beforehand. +func (o *DisableAccountParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *DisableAccountParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/credit-system/restapi/operations/account_management/disable_account_responses.go b/services/credit-system/restapi/operations/account_management/disable_account_responses.go new file mode 100644 index 0000000..f9c6a37 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/disable_account_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// DisableAccountOKCode is the HTTP code returned for type DisableAccountOK +const DisableAccountOKCode int = 200 + +/*DisableAccountOK Status information of the account with provided id in the system after the operation succeded + +swagger:response disableAccountOK +*/ +type DisableAccountOK struct { + + /* + In: Body + */ + Payload *models.AccountStatus `json:"body,omitempty"` +} + +// NewDisableAccountOK creates DisableAccountOK with default headers values +func NewDisableAccountOK() *DisableAccountOK { + + return &DisableAccountOK{} +} + +// WithPayload adds the payload to the disable account o k response +func (o *DisableAccountOK) WithPayload(payload *models.AccountStatus) *DisableAccountOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the disable account o k response +func (o *DisableAccountOK) SetPayload(payload *models.AccountStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DisableAccountOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// DisableAccountNotFoundCode is the HTTP code returned for type DisableAccountNotFound +const DisableAccountNotFoundCode int = 404 + +/*DisableAccountNotFound The account with the id provided doesn't exist + +swagger:response disableAccountNotFound +*/ +type DisableAccountNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewDisableAccountNotFound creates DisableAccountNotFound with default headers values +func NewDisableAccountNotFound() *DisableAccountNotFound { + + return &DisableAccountNotFound{} +} + +// WithPayload adds the payload to the disable account not found response +func (o *DisableAccountNotFound) WithPayload(payload *models.ErrorResponse) *DisableAccountNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the disable account not found response +func (o *DisableAccountNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DisableAccountNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// DisableAccountInternalServerErrorCode is the HTTP code returned for type DisableAccountInternalServerError +const DisableAccountInternalServerErrorCode int = 500 + +/*DisableAccountInternalServerError Something unexpected happend, error raised + +swagger:response disableAccountInternalServerError +*/ +type DisableAccountInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewDisableAccountInternalServerError creates DisableAccountInternalServerError with default headers values +func NewDisableAccountInternalServerError() *DisableAccountInternalServerError { + + return &DisableAccountInternalServerError{} +} + +// WithPayload adds the payload to the disable account internal server error response +func (o *DisableAccountInternalServerError) WithPayload(payload *models.ErrorResponse) *DisableAccountInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the disable account internal server error response +func (o *DisableAccountInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DisableAccountInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/account_management/disable_account_urlbuilder.go b/services/credit-system/restapi/operations/account_management/disable_account_urlbuilder.go new file mode 100644 index 0000000..4bf5b96 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/disable_account_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// DisableAccountURL generates an URL for the disable account operation +type DisableAccountURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *DisableAccountURL) WithBasePath(bp string) *DisableAccountURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *DisableAccountURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *DisableAccountURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/account/disable/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on DisableAccountURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *DisableAccountURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *DisableAccountURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *DisableAccountURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on DisableAccountURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on DisableAccountURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *DisableAccountURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/account_management/enable_account.go b/services/credit-system/restapi/operations/account_management/enable_account.go new file mode 100644 index 0000000..7071db5 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/enable_account.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// EnableAccountHandlerFunc turns a function with the right signature into a enable account handler +type EnableAccountHandlerFunc func(EnableAccountParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn EnableAccountHandlerFunc) Handle(params EnableAccountParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// EnableAccountHandler interface for that can handle valid enable account params +type EnableAccountHandler interface { + Handle(EnableAccountParams, interface{}) middleware.Responder +} + +// NewEnableAccount creates a new http.Handler for the enable account operation +func NewEnableAccount(ctx *middleware.Context, handler EnableAccountHandler) *EnableAccount { + return &EnableAccount{Context: ctx, Handler: handler} +} + +/*EnableAccount swagger:route POST /account/enable/{id} accountManagement enableAccount + +Enables the account with the id provided in the system + +*/ +type EnableAccount struct { + Context *middleware.Context + Handler EnableAccountHandler +} + +func (o *EnableAccount) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewEnableAccountParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/account_management/enable_account_parameters.go b/services/credit-system/restapi/operations/account_management/enable_account_parameters.go new file mode 100644 index 0000000..7dc0553 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/enable_account_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewEnableAccountParams creates a new EnableAccountParams object +// no default values defined in spec. +func NewEnableAccountParams() EnableAccountParams { + + return EnableAccountParams{} +} + +// EnableAccountParams contains all the bound params for the enable account operation +// typically these are obtained from a http.Request +// +// swagger:parameters enableAccount +type EnableAccountParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be enabled + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewEnableAccountParams() beforehand. +func (o *EnableAccountParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *EnableAccountParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/credit-system/restapi/operations/account_management/enable_account_responses.go b/services/credit-system/restapi/operations/account_management/enable_account_responses.go new file mode 100644 index 0000000..160d669 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/enable_account_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// EnableAccountOKCode is the HTTP code returned for type EnableAccountOK +const EnableAccountOKCode int = 200 + +/*EnableAccountOK Status information of the account with provided id in the system after the operation succeded + +swagger:response enableAccountOK +*/ +type EnableAccountOK struct { + + /* + In: Body + */ + Payload *models.AccountStatus `json:"body,omitempty"` +} + +// NewEnableAccountOK creates EnableAccountOK with default headers values +func NewEnableAccountOK() *EnableAccountOK { + + return &EnableAccountOK{} +} + +// WithPayload adds the payload to the enable account o k response +func (o *EnableAccountOK) WithPayload(payload *models.AccountStatus) *EnableAccountOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the enable account o k response +func (o *EnableAccountOK) SetPayload(payload *models.AccountStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *EnableAccountOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// EnableAccountNotFoundCode is the HTTP code returned for type EnableAccountNotFound +const EnableAccountNotFoundCode int = 404 + +/*EnableAccountNotFound The account with the id provided doesn't exist + +swagger:response enableAccountNotFound +*/ +type EnableAccountNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewEnableAccountNotFound creates EnableAccountNotFound with default headers values +func NewEnableAccountNotFound() *EnableAccountNotFound { + + return &EnableAccountNotFound{} +} + +// WithPayload adds the payload to the enable account not found response +func (o *EnableAccountNotFound) WithPayload(payload *models.ErrorResponse) *EnableAccountNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the enable account not found response +func (o *EnableAccountNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *EnableAccountNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// EnableAccountInternalServerErrorCode is the HTTP code returned for type EnableAccountInternalServerError +const EnableAccountInternalServerErrorCode int = 500 + +/*EnableAccountInternalServerError Something unexpected happend, error raised + +swagger:response enableAccountInternalServerError +*/ +type EnableAccountInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewEnableAccountInternalServerError creates EnableAccountInternalServerError with default headers values +func NewEnableAccountInternalServerError() *EnableAccountInternalServerError { + + return &EnableAccountInternalServerError{} +} + +// WithPayload adds the payload to the enable account internal server error response +func (o *EnableAccountInternalServerError) WithPayload(payload *models.ErrorResponse) *EnableAccountInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the enable account internal server error response +func (o *EnableAccountInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *EnableAccountInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/account_management/enable_account_urlbuilder.go b/services/credit-system/restapi/operations/account_management/enable_account_urlbuilder.go new file mode 100644 index 0000000..3650b22 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/enable_account_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// EnableAccountURL generates an URL for the enable account operation +type EnableAccountURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *EnableAccountURL) WithBasePath(bp string) *EnableAccountURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *EnableAccountURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *EnableAccountURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/account/enable/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on EnableAccountURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *EnableAccountURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *EnableAccountURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *EnableAccountURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on EnableAccountURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on EnableAccountURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *EnableAccountURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/account_management/get_account_status.go b/services/credit-system/restapi/operations/account_management/get_account_status.go new file mode 100644 index 0000000..cabb687 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/get_account_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetAccountStatusHandlerFunc turns a function with the right signature into a get account status handler +type GetAccountStatusHandlerFunc func(GetAccountStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetAccountStatusHandlerFunc) Handle(params GetAccountStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetAccountStatusHandler interface for that can handle valid get account status params +type GetAccountStatusHandler interface { + Handle(GetAccountStatusParams, interface{}) middleware.Responder +} + +// NewGetAccountStatus creates a new http.Handler for the get account status operation +func NewGetAccountStatus(ctx *middleware.Context, handler GetAccountStatusHandler) *GetAccountStatus { + return &GetAccountStatus{Context: ctx, Handler: handler} +} + +/*GetAccountStatus swagger:route GET /account/status/{id} accountManagement getAccountStatus + +Basic status of the account with the id provided in the system + +*/ +type GetAccountStatus struct { + Context *middleware.Context + Handler GetAccountStatusHandler +} + +func (o *GetAccountStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetAccountStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/account_management/get_account_status_parameters.go b/services/credit-system/restapi/operations/account_management/get_account_status_parameters.go new file mode 100644 index 0000000..e009fc9 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/get_account_status_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetAccountStatusParams creates a new GetAccountStatusParams object +// no default values defined in spec. +func NewGetAccountStatusParams() GetAccountStatusParams { + + return GetAccountStatusParams{} +} + +// GetAccountStatusParams contains all the bound params for the get account status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getAccountStatus +type GetAccountStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetAccountStatusParams() beforehand. +func (o *GetAccountStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetAccountStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/credit-system/restapi/operations/account_management/get_account_status_responses.go b/services/credit-system/restapi/operations/account_management/get_account_status_responses.go new file mode 100644 index 0000000..052b74f --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/get_account_status_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetAccountStatusOKCode is the HTTP code returned for type GetAccountStatusOK +const GetAccountStatusOKCode int = 200 + +/*GetAccountStatusOK Status information of the account with provided id in the system + +swagger:response getAccountStatusOK +*/ +type GetAccountStatusOK struct { + + /* + In: Body + */ + Payload *models.AccountStatus `json:"body,omitempty"` +} + +// NewGetAccountStatusOK creates GetAccountStatusOK with default headers values +func NewGetAccountStatusOK() *GetAccountStatusOK { + + return &GetAccountStatusOK{} +} + +// WithPayload adds the payload to the get account status o k response +func (o *GetAccountStatusOK) WithPayload(payload *models.AccountStatus) *GetAccountStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get account status o k response +func (o *GetAccountStatusOK) SetPayload(payload *models.AccountStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetAccountStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetAccountStatusNotFoundCode is the HTTP code returned for type GetAccountStatusNotFound +const GetAccountStatusNotFoundCode int = 404 + +/*GetAccountStatusNotFound The account with the id provided doesn't exist + +swagger:response getAccountStatusNotFound +*/ +type GetAccountStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetAccountStatusNotFound creates GetAccountStatusNotFound with default headers values +func NewGetAccountStatusNotFound() *GetAccountStatusNotFound { + + return &GetAccountStatusNotFound{} +} + +// WithPayload adds the payload to the get account status not found response +func (o *GetAccountStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetAccountStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get account status not found response +func (o *GetAccountStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetAccountStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetAccountStatusInternalServerErrorCode is the HTTP code returned for type GetAccountStatusInternalServerError +const GetAccountStatusInternalServerErrorCode int = 500 + +/*GetAccountStatusInternalServerError Something unexpected happend, error raised + +swagger:response getAccountStatusInternalServerError +*/ +type GetAccountStatusInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetAccountStatusInternalServerError creates GetAccountStatusInternalServerError with default headers values +func NewGetAccountStatusInternalServerError() *GetAccountStatusInternalServerError { + + return &GetAccountStatusInternalServerError{} +} + +// WithPayload adds the payload to the get account status internal server error response +func (o *GetAccountStatusInternalServerError) WithPayload(payload *models.ErrorResponse) *GetAccountStatusInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get account status internal server error response +func (o *GetAccountStatusInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetAccountStatusInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/account_management/get_account_status_urlbuilder.go b/services/credit-system/restapi/operations/account_management/get_account_status_urlbuilder.go new file mode 100644 index 0000000..b998115 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/get_account_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetAccountStatusURL generates an URL for the get account status operation +type GetAccountStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetAccountStatusURL) WithBasePath(bp string) *GetAccountStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetAccountStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetAccountStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/account/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetAccountStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetAccountStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetAccountStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetAccountStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetAccountStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetAccountStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetAccountStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/account_management/list_accounts.go b/services/credit-system/restapi/operations/account_management/list_accounts.go new file mode 100644 index 0000000..027c236 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/list_accounts.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListAccountsHandlerFunc turns a function with the right signature into a list accounts handler +type ListAccountsHandlerFunc func(ListAccountsParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListAccountsHandlerFunc) Handle(params ListAccountsParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListAccountsHandler interface for that can handle valid list accounts params +type ListAccountsHandler interface { + Handle(ListAccountsParams, interface{}) middleware.Responder +} + +// NewListAccounts creates a new http.Handler for the list accounts operation +func NewListAccounts(ctx *middleware.Context, handler ListAccountsHandler) *ListAccounts { + return &ListAccounts{Context: ctx, Handler: handler} +} + +/*ListAccounts swagger:route GET /account/list accountManagement listAccounts + +List of the accounts in the system + +*/ +type ListAccounts struct { + Context *middleware.Context + Handler ListAccountsHandler +} + +func (o *ListAccounts) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListAccountsParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/account_management/list_accounts_parameters.go b/services/credit-system/restapi/operations/account_management/list_accounts_parameters.go new file mode 100644 index 0000000..daeb38b --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/list_accounts_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListAccountsParams creates a new ListAccountsParams object +// no default values defined in spec. +func NewListAccountsParams() ListAccountsParams { + + return ListAccountsParams{} +} + +// ListAccountsParams contains all the bound params for the list accounts operation +// typically these are obtained from a http.Request +// +// swagger:parameters listAccounts +type ListAccountsParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListAccountsParams() beforehand. +func (o *ListAccountsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/restapi/operations/account_management/list_accounts_responses.go b/services/credit-system/restapi/operations/account_management/list_accounts_responses.go new file mode 100644 index 0000000..703ccdf --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/list_accounts_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// ListAccountsOKCode is the HTTP code returned for type ListAccountsOK +const ListAccountsOKCode int = 200 + +/*ListAccountsOK List of accounts in the system + +swagger:response listAccountsOK +*/ +type ListAccountsOK struct { + + /* + In: Body + */ + Payload []*models.AccountStatus `json:"body,omitempty"` +} + +// NewListAccountsOK creates ListAccountsOK with default headers values +func NewListAccountsOK() *ListAccountsOK { + + return &ListAccountsOK{} +} + +// WithPayload adds the payload to the list accounts o k response +func (o *ListAccountsOK) WithPayload(payload []*models.AccountStatus) *ListAccountsOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list accounts o k response +func (o *ListAccountsOK) SetPayload(payload []*models.AccountStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListAccountsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.AccountStatus, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListAccountsInternalServerErrorCode is the HTTP code returned for type ListAccountsInternalServerError +const ListAccountsInternalServerErrorCode int = 500 + +/*ListAccountsInternalServerError Something unexpected happend, error raised + +swagger:response listAccountsInternalServerError +*/ +type ListAccountsInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListAccountsInternalServerError creates ListAccountsInternalServerError with default headers values +func NewListAccountsInternalServerError() *ListAccountsInternalServerError { + + return &ListAccountsInternalServerError{} +} + +// WithPayload adds the payload to the list accounts internal server error response +func (o *ListAccountsInternalServerError) WithPayload(payload *models.ErrorResponse) *ListAccountsInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list accounts internal server error response +func (o *ListAccountsInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListAccountsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/account_management/list_accounts_urlbuilder.go b/services/credit-system/restapi/operations/account_management/list_accounts_urlbuilder.go new file mode 100644 index 0000000..cc79d39 --- /dev/null +++ b/services/credit-system/restapi/operations/account_management/list_accounts_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package account_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListAccountsURL generates an URL for the list accounts operation +type ListAccountsURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListAccountsURL) WithBasePath(bp string) *ListAccountsURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListAccountsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListAccountsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/account/list" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListAccountsURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListAccountsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListAccountsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListAccountsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListAccountsURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListAccountsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/credit_management/add_consumption.go b/services/credit-system/restapi/operations/credit_management/add_consumption.go new file mode 100644 index 0000000..9802cdc --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/add_consumption.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// AddConsumptionHandlerFunc turns a function with the right signature into a add consumption handler +type AddConsumptionHandlerFunc func(AddConsumptionParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn AddConsumptionHandlerFunc) Handle(params AddConsumptionParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// AddConsumptionHandler interface for that can handle valid add consumption params +type AddConsumptionHandler interface { + Handle(AddConsumptionParams, interface{}) middleware.Responder +} + +// NewAddConsumption creates a new http.Handler for the add consumption operation +func NewAddConsumption(ctx *middleware.Context, handler AddConsumptionHandler) *AddConsumption { + return &AddConsumption{Context: ctx, Handler: handler} +} + +/*AddConsumption swagger:route POST /{medium}/consume/{id} creditManagement addConsumption + +Adds a consumption to the system + +*/ +type AddConsumption struct { + Context *middleware.Context + Handler AddConsumptionHandler +} + +func (o *AddConsumption) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewAddConsumptionParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/credit_management/add_consumption_parameters.go b/services/credit-system/restapi/operations/credit_management/add_consumption_parameters.go new file mode 100644 index 0000000..7c24b18 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/add_consumption_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// NewAddConsumptionParams creates a new AddConsumptionParams object +// no default values defined in spec. +func NewAddConsumptionParams() AddConsumptionParams { + + return AddConsumptionParams{} +} + +// AddConsumptionParams contains all the bound params for the add consumption operation +// typically these are obtained from a http.Request +// +// swagger:parameters addConsumption +type AddConsumptionParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Amount to be decreased + Required: true + In: query + */ + Amount float64 + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Medium (cash/credit) to be used in the accounting + Required: true + In: path + */ + Medium string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewAddConsumptionParams() beforehand. +func (o *AddConsumptionParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qAmount, qhkAmount, _ := qs.GetOK("amount") + if err := o.bindAmount(qAmount, qhkAmount, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + rMedium, rhkMedium, _ := route.Params.GetOK("medium") + if err := o.bindMedium(rMedium, rhkMedium, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindAmount binds and validates parameter Amount from query. +func (o *AddConsumptionParams) bindAmount(rawData []string, hasKey bool, formats strfmt.Registry) error { + if !hasKey { + return errors.Required("amount", "query", rawData) + } + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // AllowEmptyValue: false + if err := validate.RequiredString("amount", "query", raw); err != nil { + return err + } + + value, err := swag.ConvertFloat64(raw) + if err != nil { + return errors.InvalidType("amount", "query", "float64", raw) + } + o.Amount = value + + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *AddConsumptionParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMedium binds and validates parameter Medium from path. +func (o *AddConsumptionParams) bindMedium(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.Medium = raw + + if err := o.validateMedium(formats); err != nil { + return err + } + + return nil +} + +// validateMedium carries on validations for parameter Medium +func (o *AddConsumptionParams) validateMedium(formats strfmt.Registry) error { + + if err := validate.EnumCase("medium", "path", o.Medium, []interface{}{"credit", "cash"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/credit-system/restapi/operations/credit_management/add_consumption_responses.go b/services/credit-system/restapi/operations/credit_management/add_consumption_responses.go new file mode 100644 index 0000000..26616ac --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/add_consumption_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// AddConsumptionOKCode is the HTTP code returned for type AddConsumptionOK +const AddConsumptionOKCode int = 200 + +/*AddConsumptionOK Credit status of the account with the provided id + +swagger:response addConsumptionOK +*/ +type AddConsumptionOK struct { + + /* + In: Body + */ + Payload *models.CreditStatus `json:"body,omitempty"` +} + +// NewAddConsumptionOK creates AddConsumptionOK with default headers values +func NewAddConsumptionOK() *AddConsumptionOK { + + return &AddConsumptionOK{} +} + +// WithPayload adds the payload to the add consumption o k response +func (o *AddConsumptionOK) WithPayload(payload *models.CreditStatus) *AddConsumptionOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add consumption o k response +func (o *AddConsumptionOK) SetPayload(payload *models.CreditStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddConsumptionOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddConsumptionNotFoundCode is the HTTP code returned for type AddConsumptionNotFound +const AddConsumptionNotFoundCode int = 404 + +/*AddConsumptionNotFound The account with the id provided doesn't exist + +swagger:response addConsumptionNotFound +*/ +type AddConsumptionNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddConsumptionNotFound creates AddConsumptionNotFound with default headers values +func NewAddConsumptionNotFound() *AddConsumptionNotFound { + + return &AddConsumptionNotFound{} +} + +// WithPayload adds the payload to the add consumption not found response +func (o *AddConsumptionNotFound) WithPayload(payload *models.ErrorResponse) *AddConsumptionNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add consumption not found response +func (o *AddConsumptionNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddConsumptionNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddConsumptionInternalServerErrorCode is the HTTP code returned for type AddConsumptionInternalServerError +const AddConsumptionInternalServerErrorCode int = 500 + +/*AddConsumptionInternalServerError Something unexpected happend, error raised + +swagger:response addConsumptionInternalServerError +*/ +type AddConsumptionInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddConsumptionInternalServerError creates AddConsumptionInternalServerError with default headers values +func NewAddConsumptionInternalServerError() *AddConsumptionInternalServerError { + + return &AddConsumptionInternalServerError{} +} + +// WithPayload adds the payload to the add consumption internal server error response +func (o *AddConsumptionInternalServerError) WithPayload(payload *models.ErrorResponse) *AddConsumptionInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add consumption internal server error response +func (o *AddConsumptionInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddConsumptionInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/credit_management/add_consumption_urlbuilder.go b/services/credit-system/restapi/operations/credit_management/add_consumption_urlbuilder.go new file mode 100644 index 0000000..9d385c8 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/add_consumption_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// AddConsumptionURL generates an URL for the add consumption operation +type AddConsumptionURL struct { + ID string + Medium string + + Amount float64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddConsumptionURL) WithBasePath(bp string) *AddConsumptionURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddConsumptionURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *AddConsumptionURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/{medium}/consume/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on AddConsumptionURL") + } + + medium := o.Medium + if medium != "" { + _path = strings.Replace(_path, "{medium}", medium, -1) + } else { + return nil, errors.New("medium is required on AddConsumptionURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + amountQ := swag.FormatFloat64(o.Amount) + if amountQ != "" { + qs.Set("amount", amountQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *AddConsumptionURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *AddConsumptionURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *AddConsumptionURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on AddConsumptionURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on AddConsumptionURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *AddConsumptionURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/credit_management/decrease_credit.go b/services/credit-system/restapi/operations/credit_management/decrease_credit.go new file mode 100644 index 0000000..a246917 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/decrease_credit.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// DecreaseCreditHandlerFunc turns a function with the right signature into a decrease credit handler +type DecreaseCreditHandlerFunc func(DecreaseCreditParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn DecreaseCreditHandlerFunc) Handle(params DecreaseCreditParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// DecreaseCreditHandler interface for that can handle valid decrease credit params +type DecreaseCreditHandler interface { + Handle(DecreaseCreditParams, interface{}) middleware.Responder +} + +// NewDecreaseCredit creates a new http.Handler for the decrease credit operation +func NewDecreaseCredit(ctx *middleware.Context, handler DecreaseCreditHandler) *DecreaseCredit { + return &DecreaseCredit{Context: ctx, Handler: handler} +} + +/*DecreaseCredit swagger:route POST /{medium}/available/decrease/{id} creditManagement decreaseCredit + +Insert a new reseller in the system. + +*/ +type DecreaseCredit struct { + Context *middleware.Context + Handler DecreaseCreditHandler +} + +func (o *DecreaseCredit) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewDecreaseCreditParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/credit_management/decrease_credit_parameters.go b/services/credit-system/restapi/operations/credit_management/decrease_credit_parameters.go new file mode 100644 index 0000000..5a65969 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/decrease_credit_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// NewDecreaseCreditParams creates a new DecreaseCreditParams object +// no default values defined in spec. +func NewDecreaseCreditParams() DecreaseCreditParams { + + return DecreaseCreditParams{} +} + +// DecreaseCreditParams contains all the bound params for the decrease credit operation +// typically these are obtained from a http.Request +// +// swagger:parameters decreaseCredit +type DecreaseCreditParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Amount to be decreased + Required: true + In: query + */ + Amount float64 + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Medium (cash/credit) to be used in the accounting + Required: true + In: path + */ + Medium string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewDecreaseCreditParams() beforehand. +func (o *DecreaseCreditParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qAmount, qhkAmount, _ := qs.GetOK("amount") + if err := o.bindAmount(qAmount, qhkAmount, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + rMedium, rhkMedium, _ := route.Params.GetOK("medium") + if err := o.bindMedium(rMedium, rhkMedium, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindAmount binds and validates parameter Amount from query. +func (o *DecreaseCreditParams) bindAmount(rawData []string, hasKey bool, formats strfmt.Registry) error { + if !hasKey { + return errors.Required("amount", "query", rawData) + } + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // AllowEmptyValue: false + if err := validate.RequiredString("amount", "query", raw); err != nil { + return err + } + + value, err := swag.ConvertFloat64(raw) + if err != nil { + return errors.InvalidType("amount", "query", "float64", raw) + } + o.Amount = value + + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *DecreaseCreditParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMedium binds and validates parameter Medium from path. +func (o *DecreaseCreditParams) bindMedium(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.Medium = raw + + if err := o.validateMedium(formats); err != nil { + return err + } + + return nil +} + +// validateMedium carries on validations for parameter Medium +func (o *DecreaseCreditParams) validateMedium(formats strfmt.Registry) error { + + if err := validate.EnumCase("medium", "path", o.Medium, []interface{}{"credit", "cash"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/credit-system/restapi/operations/credit_management/decrease_credit_responses.go b/services/credit-system/restapi/operations/credit_management/decrease_credit_responses.go new file mode 100644 index 0000000..c59868b --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/decrease_credit_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// DecreaseCreditOKCode is the HTTP code returned for type DecreaseCreditOK +const DecreaseCreditOKCode int = 200 + +/*DecreaseCreditOK Credit status of the account with the provided id + +swagger:response decreaseCreditOK +*/ +type DecreaseCreditOK struct { + + /* + In: Body + */ + Payload *models.CreditStatus `json:"body,omitempty"` +} + +// NewDecreaseCreditOK creates DecreaseCreditOK with default headers values +func NewDecreaseCreditOK() *DecreaseCreditOK { + + return &DecreaseCreditOK{} +} + +// WithPayload adds the payload to the decrease credit o k response +func (o *DecreaseCreditOK) WithPayload(payload *models.CreditStatus) *DecreaseCreditOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the decrease credit o k response +func (o *DecreaseCreditOK) SetPayload(payload *models.CreditStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DecreaseCreditOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// DecreaseCreditNotFoundCode is the HTTP code returned for type DecreaseCreditNotFound +const DecreaseCreditNotFoundCode int = 404 + +/*DecreaseCreditNotFound The account with the id provided doesn't exist + +swagger:response decreaseCreditNotFound +*/ +type DecreaseCreditNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewDecreaseCreditNotFound creates DecreaseCreditNotFound with default headers values +func NewDecreaseCreditNotFound() *DecreaseCreditNotFound { + + return &DecreaseCreditNotFound{} +} + +// WithPayload adds the payload to the decrease credit not found response +func (o *DecreaseCreditNotFound) WithPayload(payload *models.ErrorResponse) *DecreaseCreditNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the decrease credit not found response +func (o *DecreaseCreditNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DecreaseCreditNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// DecreaseCreditInternalServerErrorCode is the HTTP code returned for type DecreaseCreditInternalServerError +const DecreaseCreditInternalServerErrorCode int = 500 + +/*DecreaseCreditInternalServerError Something unexpected happend, error raised + +swagger:response decreaseCreditInternalServerError +*/ +type DecreaseCreditInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewDecreaseCreditInternalServerError creates DecreaseCreditInternalServerError with default headers values +func NewDecreaseCreditInternalServerError() *DecreaseCreditInternalServerError { + + return &DecreaseCreditInternalServerError{} +} + +// WithPayload adds the payload to the decrease credit internal server error response +func (o *DecreaseCreditInternalServerError) WithPayload(payload *models.ErrorResponse) *DecreaseCreditInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the decrease credit internal server error response +func (o *DecreaseCreditInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DecreaseCreditInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/credit_management/decrease_credit_urlbuilder.go b/services/credit-system/restapi/operations/credit_management/decrease_credit_urlbuilder.go new file mode 100644 index 0000000..75d31b6 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/decrease_credit_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// DecreaseCreditURL generates an URL for the decrease credit operation +type DecreaseCreditURL struct { + ID string + Medium string + + Amount float64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *DecreaseCreditURL) WithBasePath(bp string) *DecreaseCreditURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *DecreaseCreditURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *DecreaseCreditURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/{medium}/available/decrease/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on DecreaseCreditURL") + } + + medium := o.Medium + if medium != "" { + _path = strings.Replace(_path, "{medium}", medium, -1) + } else { + return nil, errors.New("medium is required on DecreaseCreditURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + amountQ := swag.FormatFloat64(o.Amount) + if amountQ != "" { + qs.Set("amount", amountQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *DecreaseCreditURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *DecreaseCreditURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *DecreaseCreditURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on DecreaseCreditURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on DecreaseCreditURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *DecreaseCreditURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/credit_management/get_credit.go b/services/credit-system/restapi/operations/credit_management/get_credit.go new file mode 100644 index 0000000..af49b61 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_credit.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetCreditHandlerFunc turns a function with the right signature into a get credit handler +type GetCreditHandlerFunc func(GetCreditParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetCreditHandlerFunc) Handle(params GetCreditParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetCreditHandler interface for that can handle valid get credit params +type GetCreditHandler interface { + Handle(GetCreditParams, interface{}) middleware.Responder +} + +// NewGetCredit creates a new http.Handler for the get credit operation +func NewGetCredit(ctx *middleware.Context, handler GetCreditHandler) *GetCredit { + return &GetCredit{Context: ctx, Handler: handler} +} + +/*GetCredit swagger:route GET /account/available/{id} creditManagement getCredit + +Credit status of the account with the provided id + +*/ +type GetCredit struct { + Context *middleware.Context + Handler GetCreditHandler +} + +func (o *GetCredit) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetCreditParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/credit_management/get_credit_parameters.go b/services/credit-system/restapi/operations/credit_management/get_credit_parameters.go new file mode 100644 index 0000000..0dcc8b6 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_credit_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetCreditParams creates a new GetCreditParams object +// no default values defined in spec. +func NewGetCreditParams() GetCreditParams { + + return GetCreditParams{} +} + +// GetCreditParams contains all the bound params for the get credit operation +// typically these are obtained from a http.Request +// +// swagger:parameters getCredit +type GetCreditParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetCreditParams() beforehand. +func (o *GetCreditParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetCreditParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/credit-system/restapi/operations/credit_management/get_credit_responses.go b/services/credit-system/restapi/operations/credit_management/get_credit_responses.go new file mode 100644 index 0000000..67807d5 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_credit_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetCreditOKCode is the HTTP code returned for type GetCreditOK +const GetCreditOKCode int = 200 + +/*GetCreditOK Credit status of the account with the provided id + +swagger:response getCreditOK +*/ +type GetCreditOK struct { + + /* + In: Body + */ + Payload *models.CreditStatus `json:"body,omitempty"` +} + +// NewGetCreditOK creates GetCreditOK with default headers values +func NewGetCreditOK() *GetCreditOK { + + return &GetCreditOK{} +} + +// WithPayload adds the payload to the get credit o k response +func (o *GetCreditOK) WithPayload(payload *models.CreditStatus) *GetCreditOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get credit o k response +func (o *GetCreditOK) SetPayload(payload *models.CreditStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCreditOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCreditNotFoundCode is the HTTP code returned for type GetCreditNotFound +const GetCreditNotFoundCode int = 404 + +/*GetCreditNotFound The account with the provided id doesn't exist + +swagger:response getCreditNotFound +*/ +type GetCreditNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCreditNotFound creates GetCreditNotFound with default headers values +func NewGetCreditNotFound() *GetCreditNotFound { + + return &GetCreditNotFound{} +} + +// WithPayload adds the payload to the get credit not found response +func (o *GetCreditNotFound) WithPayload(payload *models.ErrorResponse) *GetCreditNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get credit not found response +func (o *GetCreditNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCreditNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCreditInternalServerErrorCode is the HTTP code returned for type GetCreditInternalServerError +const GetCreditInternalServerErrorCode int = 500 + +/*GetCreditInternalServerError Something unexpected happend, error raised + +swagger:response getCreditInternalServerError +*/ +type GetCreditInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCreditInternalServerError creates GetCreditInternalServerError with default headers values +func NewGetCreditInternalServerError() *GetCreditInternalServerError { + + return &GetCreditInternalServerError{} +} + +// WithPayload adds the payload to the get credit internal server error response +func (o *GetCreditInternalServerError) WithPayload(payload *models.ErrorResponse) *GetCreditInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get credit internal server error response +func (o *GetCreditInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCreditInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/credit_management/get_credit_urlbuilder.go b/services/credit-system/restapi/operations/credit_management/get_credit_urlbuilder.go new file mode 100644 index 0000000..ce2cde7 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_credit_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetCreditURL generates an URL for the get credit operation +type GetCreditURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCreditURL) WithBasePath(bp string) *GetCreditURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCreditURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetCreditURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/account/available/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetCreditURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetCreditURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetCreditURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetCreditURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetCreditURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetCreditURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetCreditURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/credit_management/get_history.go b/services/credit-system/restapi/operations/credit_management/get_history.go new file mode 100644 index 0000000..76b3838 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_history.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetHistoryHandlerFunc turns a function with the right signature into a get history handler +type GetHistoryHandlerFunc func(GetHistoryParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetHistoryHandlerFunc) Handle(params GetHistoryParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetHistoryHandler interface for that can handle valid get history params +type GetHistoryHandler interface { + Handle(GetHistoryParams, interface{}) middleware.Responder +} + +// NewGetHistory creates a new http.Handler for the get history operation +func NewGetHistory(ctx *middleware.Context, handler GetHistoryHandler) *GetHistory { + return &GetHistory{Context: ctx, Handler: handler} +} + +/*GetHistory swagger:route GET /history/{id} creditManagement getHistory + +Credit history of the customer with id + +*/ +type GetHistory struct { + Context *middleware.Context + Handler GetHistoryHandler +} + +func (o *GetHistory) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetHistoryParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/credit_management/get_history_parameters.go b/services/credit-system/restapi/operations/credit_management/get_history_parameters.go new file mode 100644 index 0000000..00efdfa --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_history_parameters.go @@ -0,0 +1,149 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// NewGetHistoryParams creates a new GetHistoryParams object +// no default values defined in spec. +func NewGetHistoryParams() GetHistoryParams { + + return GetHistoryParams{} +} + +// GetHistoryParams contains all the bound params for the get history operation +// typically these are obtained from a http.Request +// +// swagger:parameters getHistory +type GetHistoryParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Boolean variable to control if the system consumptions have to be listed or not + In: query + */ + FilterSystem *bool + /*Id of the account to get the history + Required: true + In: path + */ + ID string + /*Medium (cash/credit) to be used as filter + In: query + */ + Medium *string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetHistoryParams() beforehand. +func (o *GetHistoryParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFilterSystem, qhkFilterSystem, _ := qs.GetOK("filterSystem") + if err := o.bindFilterSystem(qFilterSystem, qhkFilterSystem, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qMedium, qhkMedium, _ := qs.GetOK("medium") + if err := o.bindMedium(qMedium, qhkMedium, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFilterSystem binds and validates parameter FilterSystem from query. +func (o *GetHistoryParams) bindFilterSystem(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertBool(raw) + if err != nil { + return errors.InvalidType("filterSystem", "query", "bool", raw) + } + o.FilterSystem = &value + + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetHistoryParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMedium binds and validates parameter Medium from query. +func (o *GetHistoryParams) bindMedium(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Medium = &raw + + if err := o.validateMedium(formats); err != nil { + return err + } + + return nil +} + +// validateMedium carries on validations for parameter Medium +func (o *GetHistoryParams) validateMedium(formats strfmt.Registry) error { + + if err := validate.EnumCase("medium", "query", *o.Medium, []interface{}{"credit", "cash"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/credit-system/restapi/operations/credit_management/get_history_responses.go b/services/credit-system/restapi/operations/credit_management/get_history_responses.go new file mode 100644 index 0000000..3e9f581 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_history_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetHistoryOKCode is the HTTP code returned for type GetHistoryOK +const GetHistoryOKCode int = 200 + +/*GetHistoryOK Credit status history of the account with the provided id + +swagger:response getHistoryOK +*/ +type GetHistoryOK struct { + + /* + In: Body + */ + Payload *models.CreditHistory `json:"body,omitempty"` +} + +// NewGetHistoryOK creates GetHistoryOK with default headers values +func NewGetHistoryOK() *GetHistoryOK { + + return &GetHistoryOK{} +} + +// WithPayload adds the payload to the get history o k response +func (o *GetHistoryOK) WithPayload(payload *models.CreditHistory) *GetHistoryOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get history o k response +func (o *GetHistoryOK) SetPayload(payload *models.CreditHistory) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHistoryOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetHistoryNotFoundCode is the HTTP code returned for type GetHistoryNotFound +const GetHistoryNotFoundCode int = 404 + +/*GetHistoryNotFound The endpoint provided doesn't exist + +swagger:response getHistoryNotFound +*/ +type GetHistoryNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetHistoryNotFound creates GetHistoryNotFound with default headers values +func NewGetHistoryNotFound() *GetHistoryNotFound { + + return &GetHistoryNotFound{} +} + +// WithPayload adds the payload to the get history not found response +func (o *GetHistoryNotFound) WithPayload(payload *models.ErrorResponse) *GetHistoryNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get history not found response +func (o *GetHistoryNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHistoryNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetHistoryInternalServerErrorCode is the HTTP code returned for type GetHistoryInternalServerError +const GetHistoryInternalServerErrorCode int = 500 + +/*GetHistoryInternalServerError Something unexpected happend, error raised + +swagger:response getHistoryInternalServerError +*/ +type GetHistoryInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetHistoryInternalServerError creates GetHistoryInternalServerError with default headers values +func NewGetHistoryInternalServerError() *GetHistoryInternalServerError { + + return &GetHistoryInternalServerError{} +} + +// WithPayload adds the payload to the get history internal server error response +func (o *GetHistoryInternalServerError) WithPayload(payload *models.ErrorResponse) *GetHistoryInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get history internal server error response +func (o *GetHistoryInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHistoryInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/credit_management/get_history_urlbuilder.go b/services/credit-system/restapi/operations/credit_management/get_history_urlbuilder.go new file mode 100644 index 0000000..af4218e --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/get_history_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// GetHistoryURL generates an URL for the get history operation +type GetHistoryURL struct { + ID string + + FilterSystem *bool + Medium *string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHistoryURL) WithBasePath(bp string) *GetHistoryURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHistoryURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetHistoryURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/history/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetHistoryURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var filterSystemQ string + if o.FilterSystem != nil { + filterSystemQ = swag.FormatBool(*o.FilterSystem) + } + if filterSystemQ != "" { + qs.Set("filterSystem", filterSystemQ) + } + + var mediumQ string + if o.Medium != nil { + mediumQ = *o.Medium + } + if mediumQ != "" { + qs.Set("medium", mediumQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetHistoryURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetHistoryURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetHistoryURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetHistoryURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetHistoryURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetHistoryURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/credit_management/increase_credit.go b/services/credit-system/restapi/operations/credit_management/increase_credit.go new file mode 100644 index 0000000..3f6efaa --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/increase_credit.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// IncreaseCreditHandlerFunc turns a function with the right signature into a increase credit handler +type IncreaseCreditHandlerFunc func(IncreaseCreditParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn IncreaseCreditHandlerFunc) Handle(params IncreaseCreditParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// IncreaseCreditHandler interface for that can handle valid increase credit params +type IncreaseCreditHandler interface { + Handle(IncreaseCreditParams, interface{}) middleware.Responder +} + +// NewIncreaseCredit creates a new http.Handler for the increase credit operation +func NewIncreaseCredit(ctx *middleware.Context, handler IncreaseCreditHandler) *IncreaseCredit { + return &IncreaseCredit{Context: ctx, Handler: handler} +} + +/*IncreaseCredit swagger:route POST /{medium}/available/increase/{id} creditManagement increaseCredit + +Insert a new reseller in the system. + +*/ +type IncreaseCredit struct { + Context *middleware.Context + Handler IncreaseCreditHandler +} + +func (o *IncreaseCredit) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewIncreaseCreditParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/credit_management/increase_credit_parameters.go b/services/credit-system/restapi/operations/credit_management/increase_credit_parameters.go new file mode 100644 index 0000000..96c68df --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/increase_credit_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// NewIncreaseCreditParams creates a new IncreaseCreditParams object +// no default values defined in spec. +func NewIncreaseCreditParams() IncreaseCreditParams { + + return IncreaseCreditParams{} +} + +// IncreaseCreditParams contains all the bound params for the increase credit operation +// typically these are obtained from a http.Request +// +// swagger:parameters increaseCredit +type IncreaseCreditParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Amount to be inccreased + Required: true + In: query + */ + Amount float64 + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Medium (cash/credit) to be used in the accounting + Required: true + In: path + */ + Medium string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewIncreaseCreditParams() beforehand. +func (o *IncreaseCreditParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qAmount, qhkAmount, _ := qs.GetOK("amount") + if err := o.bindAmount(qAmount, qhkAmount, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + rMedium, rhkMedium, _ := route.Params.GetOK("medium") + if err := o.bindMedium(rMedium, rhkMedium, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindAmount binds and validates parameter Amount from query. +func (o *IncreaseCreditParams) bindAmount(rawData []string, hasKey bool, formats strfmt.Registry) error { + if !hasKey { + return errors.Required("amount", "query", rawData) + } + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // AllowEmptyValue: false + if err := validate.RequiredString("amount", "query", raw); err != nil { + return err + } + + value, err := swag.ConvertFloat64(raw) + if err != nil { + return errors.InvalidType("amount", "query", "float64", raw) + } + o.Amount = value + + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *IncreaseCreditParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMedium binds and validates parameter Medium from path. +func (o *IncreaseCreditParams) bindMedium(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.Medium = raw + + if err := o.validateMedium(formats); err != nil { + return err + } + + return nil +} + +// validateMedium carries on validations for parameter Medium +func (o *IncreaseCreditParams) validateMedium(formats strfmt.Registry) error { + + if err := validate.EnumCase("medium", "path", o.Medium, []interface{}{"credit", "cash"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/credit-system/restapi/operations/credit_management/increase_credit_responses.go b/services/credit-system/restapi/operations/credit_management/increase_credit_responses.go new file mode 100644 index 0000000..3c1051e --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/increase_credit_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// IncreaseCreditOKCode is the HTTP code returned for type IncreaseCreditOK +const IncreaseCreditOKCode int = 200 + +/*IncreaseCreditOK Credit status of the account with the provided id + +swagger:response increaseCreditOK +*/ +type IncreaseCreditOK struct { + + /* + In: Body + */ + Payload *models.CreditStatus `json:"body,omitempty"` +} + +// NewIncreaseCreditOK creates IncreaseCreditOK with default headers values +func NewIncreaseCreditOK() *IncreaseCreditOK { + + return &IncreaseCreditOK{} +} + +// WithPayload adds the payload to the increase credit o k response +func (o *IncreaseCreditOK) WithPayload(payload *models.CreditStatus) *IncreaseCreditOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the increase credit o k response +func (o *IncreaseCreditOK) SetPayload(payload *models.CreditStatus) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *IncreaseCreditOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// IncreaseCreditNotFoundCode is the HTTP code returned for type IncreaseCreditNotFound +const IncreaseCreditNotFoundCode int = 404 + +/*IncreaseCreditNotFound The account with the id provided doesn't exist + +swagger:response increaseCreditNotFound +*/ +type IncreaseCreditNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewIncreaseCreditNotFound creates IncreaseCreditNotFound with default headers values +func NewIncreaseCreditNotFound() *IncreaseCreditNotFound { + + return &IncreaseCreditNotFound{} +} + +// WithPayload adds the payload to the increase credit not found response +func (o *IncreaseCreditNotFound) WithPayload(payload *models.ErrorResponse) *IncreaseCreditNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the increase credit not found response +func (o *IncreaseCreditNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *IncreaseCreditNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// IncreaseCreditInternalServerErrorCode is the HTTP code returned for type IncreaseCreditInternalServerError +const IncreaseCreditInternalServerErrorCode int = 500 + +/*IncreaseCreditInternalServerError Something unexpected happend, error raised + +swagger:response increaseCreditInternalServerError +*/ +type IncreaseCreditInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewIncreaseCreditInternalServerError creates IncreaseCreditInternalServerError with default headers values +func NewIncreaseCreditInternalServerError() *IncreaseCreditInternalServerError { + + return &IncreaseCreditInternalServerError{} +} + +// WithPayload adds the payload to the increase credit internal server error response +func (o *IncreaseCreditInternalServerError) WithPayload(payload *models.ErrorResponse) *IncreaseCreditInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the increase credit internal server error response +func (o *IncreaseCreditInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *IncreaseCreditInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/credit_management/increase_credit_urlbuilder.go b/services/credit-system/restapi/operations/credit_management/increase_credit_urlbuilder.go new file mode 100644 index 0000000..58603db --- /dev/null +++ b/services/credit-system/restapi/operations/credit_management/increase_credit_urlbuilder.go @@ -0,0 +1,120 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package credit_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// IncreaseCreditURL generates an URL for the increase credit operation +type IncreaseCreditURL struct { + ID string + Medium string + + Amount float64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *IncreaseCreditURL) WithBasePath(bp string) *IncreaseCreditURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *IncreaseCreditURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *IncreaseCreditURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/{medium}/available/increase/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on IncreaseCreditURL") + } + + medium := o.Medium + if medium != "" { + _path = strings.Replace(_path, "{medium}", medium, -1) + } else { + return nil, errors.New("medium is required on IncreaseCreditURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + amountQ := swag.FormatFloat64(o.Amount) + if amountQ != "" { + qs.Set("amount", amountQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *IncreaseCreditURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *IncreaseCreditURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *IncreaseCreditURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on IncreaseCreditURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on IncreaseCreditURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *IncreaseCreditURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/credit_manager_management_api_api.go b/services/credit-system/restapi/operations/credit_manager_management_api_api.go new file mode 100644 index 0000000..5bdd958 --- /dev/null +++ b/services/credit-system/restapi/operations/credit_manager_management_api_api.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/account_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/credit_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/trigger_management" +) + +// NewCreditManagerManagementAPIAPI creates a new CreditManagerManagementAPI instance +func NewCreditManagerManagementAPIAPI(spec *loads.Document) *CreditManagerManagementAPIAPI { + return &CreditManagerManagementAPIAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + useSwaggerUI: false, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + CreditManagementAddConsumptionHandler: credit_management.AddConsumptionHandlerFunc(func(params credit_management.AddConsumptionParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation credit_management.AddConsumption has not yet been implemented") + }), + AccountManagementCreateAccountHandler: account_management.CreateAccountHandlerFunc(func(params account_management.CreateAccountParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation account_management.CreateAccount has not yet been implemented") + }), + CreditManagementDecreaseCreditHandler: credit_management.DecreaseCreditHandlerFunc(func(params credit_management.DecreaseCreditParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation credit_management.DecreaseCredit has not yet been implemented") + }), + AccountManagementDisableAccountHandler: account_management.DisableAccountHandlerFunc(func(params account_management.DisableAccountParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation account_management.DisableAccount has not yet been implemented") + }), + AccountManagementEnableAccountHandler: account_management.EnableAccountHandlerFunc(func(params account_management.EnableAccountParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation account_management.EnableAccount has not yet been implemented") + }), + TriggerManagementExecSampleHandler: trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.ExecSample has not yet been implemented") + }), + AccountManagementGetAccountStatusHandler: account_management.GetAccountStatusHandlerFunc(func(params account_management.GetAccountStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation account_management.GetAccountStatus has not yet been implemented") + }), + CreditManagementGetCreditHandler: credit_management.GetCreditHandlerFunc(func(params credit_management.GetCreditParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation credit_management.GetCredit has not yet been implemented") + }), + CreditManagementGetHistoryHandler: credit_management.GetHistoryHandlerFunc(func(params credit_management.GetHistoryParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation credit_management.GetHistory has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + CreditManagementIncreaseCreditHandler: credit_management.IncreaseCreditHandlerFunc(func(params credit_management.IncreaseCreditParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation credit_management.IncreaseCredit has not yet been implemented") + }), + AccountManagementListAccountsHandler: account_management.ListAccountsHandlerFunc(func(params account_management.ListAccountsParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation account_management.ListAccounts has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*CreditManagerManagementAPIAPI An API which supports creation, deletion, listing etc of Credit Manager */ +type CreditManagerManagementAPIAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + useSwaggerUI bool + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // CreditManagementAddConsumptionHandler sets the operation handler for the add consumption operation + CreditManagementAddConsumptionHandler credit_management.AddConsumptionHandler + // AccountManagementCreateAccountHandler sets the operation handler for the create account operation + AccountManagementCreateAccountHandler account_management.CreateAccountHandler + // CreditManagementDecreaseCreditHandler sets the operation handler for the decrease credit operation + CreditManagementDecreaseCreditHandler credit_management.DecreaseCreditHandler + // AccountManagementDisableAccountHandler sets the operation handler for the disable account operation + AccountManagementDisableAccountHandler account_management.DisableAccountHandler + // AccountManagementEnableAccountHandler sets the operation handler for the enable account operation + AccountManagementEnableAccountHandler account_management.EnableAccountHandler + // TriggerManagementExecSampleHandler sets the operation handler for the exec sample operation + TriggerManagementExecSampleHandler trigger_management.ExecSampleHandler + // AccountManagementGetAccountStatusHandler sets the operation handler for the get account status operation + AccountManagementGetAccountStatusHandler account_management.GetAccountStatusHandler + // CreditManagementGetCreditHandler sets the operation handler for the get credit operation + CreditManagementGetCreditHandler credit_management.GetCreditHandler + // CreditManagementGetHistoryHandler sets the operation handler for the get history operation + CreditManagementGetHistoryHandler credit_management.GetHistoryHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // CreditManagementIncreaseCreditHandler sets the operation handler for the increase credit operation + CreditManagementIncreaseCreditHandler credit_management.IncreaseCreditHandler + // AccountManagementListAccountsHandler sets the operation handler for the list accounts operation + AccountManagementListAccountsHandler account_management.ListAccountsHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// UseRedoc for documentation at /docs +func (o *CreditManagerManagementAPIAPI) UseRedoc() { + o.useSwaggerUI = false +} + +// UseSwaggerUI for documentation at /docs +func (o *CreditManagerManagementAPIAPI) UseSwaggerUI() { + o.useSwaggerUI = true +} + +// SetDefaultProduces sets the default produces media type +func (o *CreditManagerManagementAPIAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *CreditManagerManagementAPIAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *CreditManagerManagementAPIAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *CreditManagerManagementAPIAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *CreditManagerManagementAPIAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *CreditManagerManagementAPIAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *CreditManagerManagementAPIAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the CreditManagerManagementAPIAPI +func (o *CreditManagerManagementAPIAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.CreditManagementAddConsumptionHandler == nil { + unregistered = append(unregistered, "credit_management.AddConsumptionHandler") + } + if o.AccountManagementCreateAccountHandler == nil { + unregistered = append(unregistered, "account_management.CreateAccountHandler") + } + if o.CreditManagementDecreaseCreditHandler == nil { + unregistered = append(unregistered, "credit_management.DecreaseCreditHandler") + } + if o.AccountManagementDisableAccountHandler == nil { + unregistered = append(unregistered, "account_management.DisableAccountHandler") + } + if o.AccountManagementEnableAccountHandler == nil { + unregistered = append(unregistered, "account_management.EnableAccountHandler") + } + if o.TriggerManagementExecSampleHandler == nil { + unregistered = append(unregistered, "trigger_management.ExecSampleHandler") + } + if o.AccountManagementGetAccountStatusHandler == nil { + unregistered = append(unregistered, "account_management.GetAccountStatusHandler") + } + if o.CreditManagementGetCreditHandler == nil { + unregistered = append(unregistered, "credit_management.GetCreditHandler") + } + if o.CreditManagementGetHistoryHandler == nil { + unregistered = append(unregistered, "credit_management.GetHistoryHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.CreditManagementIncreaseCreditHandler == nil { + unregistered = append(unregistered, "credit_management.IncreaseCreditHandler") + } + if o.AccountManagementListAccountsHandler == nil { + unregistered = append(unregistered, "account_management.ListAccountsHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *CreditManagerManagementAPIAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *CreditManagerManagementAPIAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *CreditManagerManagementAPIAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *CreditManagerManagementAPIAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *CreditManagerManagementAPIAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *CreditManagerManagementAPIAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the credit manager management API API +func (o *CreditManagerManagementAPIAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *CreditManagerManagementAPIAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/{medium}/consume/{id}"] = credit_management.NewAddConsumption(o.context, o.CreditManagementAddConsumptionHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/account/create/{id}"] = account_management.NewCreateAccount(o.context, o.AccountManagementCreateAccountHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/{medium}/available/decrease/{id}"] = credit_management.NewDecreaseCredit(o.context, o.CreditManagementDecreaseCreditHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/account/disable/{id}"] = account_management.NewDisableAccount(o.context, o.AccountManagementDisableAccountHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/account/enable/{id}"] = account_management.NewEnableAccount(o.context, o.AccountManagementEnableAccountHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/sample"] = trigger_management.NewExecSample(o.context, o.TriggerManagementExecSampleHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/account/status/{id}"] = account_management.NewGetAccountStatus(o.context, o.AccountManagementGetAccountStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/account/available/{id}"] = credit_management.NewGetCredit(o.context, o.CreditManagementGetCreditHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/history/{id}"] = credit_management.NewGetHistory(o.context, o.CreditManagementGetHistoryHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/{medium}/available/increase/{id}"] = credit_management.NewIncreaseCredit(o.context, o.CreditManagementIncreaseCreditHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/account/list"] = account_management.NewListAccounts(o.context, o.AccountManagementListAccountsHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *CreditManagerManagementAPIAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + if o.useSwaggerUI { + return o.context.APIHandlerSwaggerUI(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *CreditManagerManagementAPIAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *CreditManagerManagementAPIAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *CreditManagerManagementAPIAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *CreditManagerManagementAPIAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/services/credit-system/restapi/operations/status_management/get_status.go b/services/credit-system/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/status_management/get_status_parameters.go b/services/credit-system/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..a7596db --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the endpoint to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"kafka-receiver", "kafka-sender", "status", "trigger", "account", "credit"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/credit-system/restapi/operations/status_management/get_status_responses.go b/services/credit-system/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..405a6f2 --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/status_management/get_status_urlbuilder.go b/services/credit-system/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..151ece5 --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/status_management/show_status.go b/services/credit-system/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/status_management/show_status_parameters.go b/services/credit-system/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/restapi/operations/status_management/show_status_responses.go b/services/credit-system/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..236e03b --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/status_management/show_status_urlbuilder.go b/services/credit-system/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..6efc165 --- /dev/null +++ b/services/credit-system/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/operations/trigger_management/exec_sample.go b/services/credit-system/restapi/operations/trigger_management/exec_sample.go new file mode 100644 index 0000000..3a21c8a --- /dev/null +++ b/services/credit-system/restapi/operations/trigger_management/exec_sample.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ExecSampleHandlerFunc turns a function with the right signature into a exec sample handler +type ExecSampleHandlerFunc func(ExecSampleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ExecSampleHandlerFunc) Handle(params ExecSampleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ExecSampleHandler interface for that can handle valid exec sample params +type ExecSampleHandler interface { + Handle(ExecSampleParams, interface{}) middleware.Responder +} + +// NewExecSample creates a new http.Handler for the exec sample operation +func NewExecSample(ctx *middleware.Context, handler ExecSampleHandler) *ExecSample { + return &ExecSample{Context: ctx, Handler: handler} +} + +/*ExecSample swagger:route GET /trigger/sample triggerManagement execSample + +Sample task trigger + +*/ +type ExecSample struct { + Context *middleware.Context + Handler ExecSampleHandler +} + +func (o *ExecSample) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewExecSampleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/credit-system/restapi/operations/trigger_management/exec_sample_parameters.go b/services/credit-system/restapi/operations/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..e3aad65 --- /dev/null +++ b/services/credit-system/restapi/operations/trigger_management/exec_sample_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// no default values defined in spec. +func NewExecSampleParams() ExecSampleParams { + + return ExecSampleParams{} +} + +// ExecSampleParams contains all the bound params for the exec sample operation +// typically these are obtained from a http.Request +// +// swagger:parameters execSample +type ExecSampleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewExecSampleParams() beforehand. +func (o *ExecSampleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/credit-system/restapi/operations/trigger_management/exec_sample_responses.go b/services/credit-system/restapi/operations/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..d23f88c --- /dev/null +++ b/services/credit-system/restapi/operations/trigger_management/exec_sample_responses.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" +) + +// ExecSampleOKCode is the HTTP code returned for type ExecSampleOK +const ExecSampleOKCode int = 200 + +/*ExecSampleOK Sample task executed successfully + +swagger:response execSampleOK +*/ +type ExecSampleOK struct { +} + +// NewExecSampleOK creates ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + + return &ExecSampleOK{} +} + +// WriteResponse to the client +func (o *ExecSampleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// ExecSampleInternalServerErrorCode is the HTTP code returned for type ExecSampleInternalServerError +const ExecSampleInternalServerErrorCode int = 500 + +/*ExecSampleInternalServerError Something unexpected happend, error raised + +swagger:response execSampleInternalServerError +*/ +type ExecSampleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewExecSampleInternalServerError creates ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + + return &ExecSampleInternalServerError{} +} + +// WithPayload adds the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) WithPayload(payload *models.ErrorResponse) *ExecSampleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ExecSampleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/credit-system/restapi/operations/trigger_management/exec_sample_urlbuilder.go b/services/credit-system/restapi/operations/trigger_management/exec_sample_urlbuilder.go new file mode 100644 index 0000000..33b621a --- /dev/null +++ b/services/credit-system/restapi/operations/trigger_management/exec_sample_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ExecSampleURL generates an URL for the exec sample operation +type ExecSampleURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) WithBasePath(bp string) *ExecSampleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ExecSampleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/sample" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ExecSampleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ExecSampleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ExecSampleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ExecSampleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ExecSampleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ExecSampleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/credit-system/restapi/server.go b/services/credit-system/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/services/credit-system/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/services/credit-system/run/cert.crt b/services/credit-system/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/credit-system/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/credit-system/run/config.toml b/services/credit-system/run/config.toml new file mode 100644 index 0000000..1bd9381 --- /dev/null +++ b/services/credit-system/run/config.toml @@ -0,0 +1,89 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "23h" +DBName = "cyclops" +Host = "localhost" +Password = "pass1234" +Port = 5432 +# SSLMode = enable | disable +SSLMode = "disable" +UserName = "cyclops" + +[EVENTS] +Filters = [ "filter1", "filter2" ] + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +# "" for no file-logging +LogFile = "" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8000" +CDR = "cdr:8000" +CreditManager = "creditsystem:8000" +CustomerDB = "customerdb:8000" +EventsEngine = "eventsengine:8000" +PlanManager = "planmanager:8000" +UDR = "udr:8000" + +[KAFKA] +Brokers = [ "kafka1:9092", "kafka2:9092", "kafka3:9092" ] +CDRIn = [ "CDR" ] +CDROut = [ "Credit" ] +Credit-SystemIn = [ "Credit" ] +EventsEngineIn = [ "Events" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMin = 10e3 +SizeMax = 10e6 +UDRIn = [ "UDR" ] +UDROut = [ "CDR" ] + +[PLANS] +Default = "-1" +Education = "-2" + +[PROMETHEUS] +Host = "prometheus:9090" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + diff --git a/services/credit-system/run/docker-compose.yml b/services/credit-system/run/docker-compose.yml new file mode 100644 index 0000000..8a6e52e --- /dev/null +++ b/services/credit-system/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: SERVICE:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/services/credit-system/run/key.key b/services/credit-system/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/credit-system/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/credit-system/server/accountManager/accountManager.go b/services/credit-system/server/accountManager/accountManager.go new file mode 100644 index 0000000..d24d321 --- /dev/null +++ b/services/credit-system/server/accountManager/accountManager.go @@ -0,0 +1,282 @@ +package accountManager + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/account_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// AccountManager is the struct defined to group and contain all the methods +// that interact with the accounts endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type AccountManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct AccountManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// Returns: +// - AccountManager: struct to interact with AccountManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *AccountManager { + + l.Trace.Printf("[AccountManager] Gerenating new AccountManager.\n") + + monit.InitEndpoint("account") + + return &AccountManager{ + db: db, + monit: monit, + } + +} + +// CreateAccount (Swagger func) is the function behind the (POST) API Endpoint +// /account/create/{id} +// Its job is to create a new credit account in the system with the ID provided. +func (m *AccountManager) CreateAccount(ctx context.Context, params account_management.CreateAccountParams) middleware.Responder { + + l.Trace.Printf("[AccountManager] CreateAccount endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("account", callTime) + + accountStatus, e := m.db.CreateAccount(params.ID) + + if e != nil { + + s := "Problem creating the Account: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewCreateAccountInternalServerError().WithPayload(&errorReturn) + + } + + if accountStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusCreated), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewCreateAccountCreated().WithPayload(accountStatus) + + } + + s := "The Account already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusConflict), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewCreateAccountConflict().WithPayload(&conflictReturn) + +} + +// DisableAccount (Swagger func) is the function behind the (POST) API Endpoint +// /account/disable/{id} +// Its job is to disable an account existing in the system given its ID. +func (m *AccountManager) DisableAccount(ctx context.Context, params account_management.DisableAccountParams) middleware.Responder { + + l.Trace.Printf("[AccountManager] DisableAccount endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("account", callTime) + + accountStatus, e := m.db.DisableAccount(params.ID) + + if e != nil { + + s := "Problem creating the Account: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewDisableAccountInternalServerError().WithPayload(&errorReturn) + + } + + if accountStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewDisableAccountOK().WithPayload(accountStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewDisableAccountNotFound().WithPayload(&missingReturn) + +} + +// EnableAccount (Swagger func) is the function behind the (POST) API Endpoint +// /account/enable/{id} +// Its job is to enable an account existing in the system given its ID. +func (m *AccountManager) EnableAccount(ctx context.Context, params account_management.EnableAccountParams) middleware.Responder { + + l.Trace.Printf("[AccountManager] EnableAccount endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("account", callTime) + + accountStatus, e := m.db.EnableAccount(params.ID) + + if e != nil { + + s := "Problem creating the Account: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewEnableAccountInternalServerError().WithPayload(&errorReturn) + + } + + if accountStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewEnableAccountOK().WithPayload(accountStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewEnableAccountNotFound().WithPayload(&missingReturn) + +} + +// GetAccountStatus (Swagger func) is the function behind the (GET) API Endpoint +// /account/status/{id} +// Its job is to get the status of an account existing in the system given its ID. +func (m *AccountManager) GetAccountStatus(ctx context.Context, params account_management.GetAccountStatusParams) middleware.Responder { + + l.Trace.Printf("[AccountManager] GetAccountStatus endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("account", callTime) + + accountStatus, e := m.db.GetAccountStatus(params.ID) + + if e != nil { + + s := "Problem creating the Account: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewGetAccountStatusInternalServerError().WithPayload(&errorReturn) + + } + + if accountStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewGetAccountStatusOK().WithPayload(accountStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewGetAccountStatusNotFound().WithPayload(&missingReturn) + +} + +// ListAccounts (Swagger func) is the function behind the (GET) API Endpoint +// /account/list +// Its job is to list all the account existing in the system. +func (m *AccountManager) ListAccounts(ctx context.Context, params account_management.ListAccountsParams) middleware.Responder { + + l.Trace.Printf("[AccountManager] ListAccounts endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("account", callTime) + + accountsList, e := m.db.ListAccounts() + + if e != nil { + + s := "Problem creating the Account: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewListAccountsInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("account", callTime) + + return account_management.NewListAccountsOK().WithPayload(accountsList) + +} diff --git a/services/credit-system/server/cache.go b/services/credit-system/server/cache.go new file mode 100644 index 0000000..ec267cc --- /dev/null +++ b/services/credit-system/server/cache.go @@ -0,0 +1,553 @@ +package main + +import ( + "context" + "net/url" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + cdrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client" + cdrUsage "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/usage_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/cacheManager" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + cusCustomer "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/customer_management" + cusProduct "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/product_management" + cusReseller "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/reseller_management" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + pmBundle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/bundle_management" + pmCycle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/cycle_management" + pmPlan "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/plan_management" + pmSku "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/sku_management" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheStart handles the initialization of the cache mechanism service. +// Returns: +// - A cacheManager reference struct already initialized and ready to be used. +func cacheStart(metrics *prometheus.GaugeVec) *cacheManager.CacheManager { + + l.Trace.Printf("[CACHE][INIT] Intializing cache mechanism.\n") + + cacheDuration, _ := time.ParseDuration(cfg.DB.CacheRetention) + + c := cacheManager.New(metrics, cacheDuration, cfg.APIKey.Token) + + resellerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusReseller.NewGetResellerParams().WithID(i) + + r, e := client.ResellerManagement.GetReseller(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the reseller with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusReseller.NewListResellersParams() + + r, e := client.ResellerManagement.ListResellers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of resellers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + customerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusCustomer.NewGetCustomerParams().WithID(i) + + r, e := client.CustomerManagement.GetCustomer(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the customer with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusCustomer.NewListCustomersParams() + + r, e := client.CustomerManagement.ListCustomers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of customers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + productFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusProduct.NewGetProductParams().WithID(i) + + r, e := client.ProductManagement.GetProduct(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the product with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusProduct.NewListProductsParams() + + r, e := client.ProductManagement.ListProducts(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of products. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + // id == id0[,id1,...,idN]?from?to + cdrFunction := func(id interface{}, token string) (interface{}, error) { + + config := cdrClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["cdr"], + Path: cdrClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + idSplit := strings.SplitN(id.(string), "?", 3) + + i := idSplit[0] + + from, e := time.Parse(time.RFC3339Nano, idSplit[1]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[1], e) + + return nil, e + + } + + f := (strfmt.DateTime)(from) + + to, e := time.Parse(time.RFC3339Nano, idSplit[2]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[2], e) + + return nil, e + + } + + t := (strfmt.DateTime)(to) + + client := cdrClient.New(config) + ctx := context.Background() + + if strings.Contains(i, ",") { + + params := cdrUsage.NewGetSystemUsageParams().WithIdlist(&i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + if i != "ALL" { + + params := cdrUsage.NewGetUsageParams().WithID(i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving the CDRs under the id [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := cdrUsage.NewGetSystemUsageParams().WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + skuFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmSku.NewGetSkuParams().WithID(id.(string)) + + r, e := client.SkuManagement.GetSku(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the sku [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := pmSku.NewListSkusParams() + + r, e := client.SkuManagement.ListSkus(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the skus list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + planFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + var planID string + + if i, exists := cfg.DefaultPlans[strings.ToLower(id.(string))]; exists { + + planID = i + + } else { + + planID = id.(string) + + } + + params := pmPlan.NewGetCompletePlanParams().WithID(planID) + + r, e := client.PlanManagement.GetCompletePlan(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmPlan.NewListCompletePlansParams() + + r, e := client.PlanManagement.ListCompletePlans(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + bundleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmBundle.NewGetSkuBundleParams().WithID(id.(string)) + + r, e := client.BundleManagement.GetSkuBundle(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmBundle.NewListSkuBundlesParams() + + r, e := client.BundleManagement.ListSkuBundles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + cycleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + var params *pmCycle.ListCyclesParams + + if id.(string) == "ALL" { + + params = pmCycle.NewListCyclesParams() + + } else { + + ty := id.(string) + + params = pmCycle.NewListCyclesParams().WithType(&ty) + + } + + r, e := client.CycleManagement.ListCycles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CYCLE-FUNCTION] There was a problem while retrieving the cycle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + c.Add("reseller", resellerFunction) + l.Trace.Printf("[CACHE][INIT] Reseller fetcher added to the cache.\n") + + c.Add("customer", customerFunction) + l.Trace.Printf("[CACHE][INIT] Customer fetcher added to the cache.\n") + + c.Add("product", productFunction) + l.Trace.Printf("[CACHE][INIT] Product fetcher added to the cache.\n") + + c.Add("cdr", cdrFunction) + l.Trace.Printf("[CACHE][INIT] CDR usage fetcher added to the cache.\n") + + c.Add("sku", skuFunction) + l.Trace.Printf("[CACHE][INIT] SKU fetcher added to the cache.\n") + + c.Add("plan", planFunction) + l.Trace.Printf("[CACHE][INIT] Plan fetcher added to the cache.\n") + + c.Add("bundle", bundleFunction) + l.Trace.Printf("[CACHE][INIT] SkuBundle fetcher added to the cache.\n") + + c.Add("cycle", cycleFunction) + l.Trace.Printf("[CACHE][INIT] Life Cycle fetcher added to the cache.\n") + + return c + +} diff --git a/services/credit-system/server/cacheManager/cacheManager.go b/services/credit-system/server/cacheManager/cacheManager.go new file mode 100644 index 0000000..9da44a3 --- /dev/null +++ b/services/credit-system/server/cacheManager/cacheManager.go @@ -0,0 +1,277 @@ +package cacheManager + +import ( + "fmt" + "strings" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheFetchFunction it will need the id to retrieve and as and option a Bearer +// Keycloak token can be provided when called. +// It shall return the object and errors in case of problems. +type cacheFetchFunction func(interface{}, string) (interface{}, error) + +// cache struct is the main "object" which handles the cache and its items. +// It also contains a map with the conversions of interfaces to strings. +type cache struct { + ////conversionDictionary map[string]string + data map[string]*cacheItem + fetchers map[string]cacheFetchFunction + mutex sync.RWMutex +} + +// cacheItem struct referes to the data of each element saved in the cache. +type cacheItem struct { + fetcher cacheFetchFunction + lastUpdate time.Time + value interface{} +} + +// CacheManager is the struct defined to group and contain all the methods +// that interact with the caching mechanism. +type CacheManager struct { + APIKey string + duration time.Duration + metrics *prometheus.GaugeVec + store cache +} + +// New is the function to create the struct CacheManager. +// Parameters: +// - t: a time.Duration with the max duration alive of the cache elements. +// - k: string containing the APIKey/token in case of need. +// Returns: +// - CacheManager: struct to interact with CacheManager subsystem functionalities. +func New(metrics *prometheus.GaugeVec, t time.Duration, k string) *CacheManager { + + l.Trace.Printf("[CACHE] Initializing the cache service.\n") + + c := CacheManager{ + APIKey: k, + duration: t, + metrics: metrics, + store: cache{ + data: make(map[string]*cacheItem), + fetchers: make(map[string]cacheFetchFunction), + }, + } + + return &c + +} + +// Add function job is to insert a new model in the cache. +// What it does is link the model with a fetching function and, if wanted, with +// a plain text name, so later in order to retrieve things from the cache they +// can be refereced either by the struct model or the plain text name. +// Paramenters: +// - plainName: a case insensitive name/alias to retrieve the data. +// - fetcher: the cacheFetchFunction used to retrieve the data. +func (c *CacheManager) Add(plainName string, fetcher cacheFetchFunction) { + + l.Trace.Printf("[CACHE] Adding a new object fetcher in the cache.\n") + + key := strings.ToUpper(plainName) + + c.store.mutex.Lock() + + c.store.fetchers[key] = fetcher + + c.store.mutex.Unlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Models in Cache"}).Inc() + + return + +} + +// fetch function job is to retrieve a new and updated copy of the remote object. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) fetch(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + c.store.mutex.RLock() + + object := c.store.data[item] + + c.store.mutex.RUnlock() + + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := object.fetcher(id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + object.value = uValue + object.lastUpdate = time.Now() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// fetch function job is to create the new item in the cache and retrieve a new +// and updated initial copy of the remote object to be saved in the cache. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) init(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + key := strings.Split(item, "-")[0] + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := c.store.fetchers[key](id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + i := cacheItem{ + fetcher: c.store.fetchers[key], + lastUpdate: time.Now(), + value: uValue, + } + + c.store.mutex.Lock() + + c.store.data[item] = &i + + c.store.mutex.Unlock() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// key is a function to ensure that the creation of the the item key for the +// cache is consistent across all the functions. +// Paramenters: +// - id: the reference id of the object to be retrieved +// - model: the alias text used to identify the source of objects. +// Returns: +// - s: the key string +func (c *CacheManager) key(id interface{}, model string) (s string) { + + s = fmt.Sprintf("%v-%v", strings.ToUpper(model), id) + + return + +} + +// Get function job is to retrieve an object from the cache or fetch it from the +// source and upgrade the copy in the cache in case the expiration time has been +// exceeded. +// Paramenters: +// - id: the reference id of the object. +// - model: the text alias set to reference the model. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - The object associated with the request +// - An error raised in case something went wrong while retrieving the object. +func (c *CacheManager) Get(id interface{}, model string, token string) (interface{}, error) { + + l.Trace.Printf("[CACHE] Retrieving object [ %v, %v ] from the cache.\n", id, model) + + item := c.key(id, model) + + object, exists := c.store.data[item] + + if !exists { + + l.Trace.Printf("[CACHE] Object [ %v ] first time requested, including in the cache.\n", item) + + if e := c.init(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while adding the new item [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects cached"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects cached"}).Inc() + + return o, nil + + } + + l.Trace.Printf("[CACHE] Object [ %v ] exists in the cache.\n", item) + + c.store.mutex.Lock() + + diff := (time.Now()).Sub(c.store.data[item].lastUpdate) + + c.store.mutex.Unlock() + + if diff <= c.duration { + + l.Trace.Printf("[CACHE] Object [ %v ] cache hasn't expired yet.\n", item) + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return object.value, nil + + } + + l.Warning.Printf("[CACHE] Object [ %v ] cache has expired. Starting the upgrade.\n", item) + + if e := c.fetch(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while fetching the updated data for the object [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects refreshed"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] updated retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects refreshed"}).Inc() + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return o, nil + +} diff --git a/services/credit-system/server/config.go b/services/credit-system/server/config.go new file mode 100644 index 0000000..4eb0cf9 --- /dev/null +++ b/services/credit-system/server/config.go @@ -0,0 +1,223 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + DefaultPlans map[string]string + Prometheus prometheusConfig +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type planConfig struct { + Default string +} +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("database.cacheretention"), + DbName: viper.GetString("database.dbname"), + Host: viper.GetString("database.host"), + Password: viper.GetString("database.password"), + Port: viper.GetInt("database.port"), + SSLMode: viper.GetString("database.sslmode"), + Username: viper.GetString("database.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + DefaultPlans: viper.GetStringMapString("plans"), + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/services/credit-system/server/creditManager/creditManager.go b/services/credit-system/server/creditManager/creditManager.go new file mode 100644 index 0000000..2a0f4e7 --- /dev/null +++ b/services/credit-system/server/creditManager/creditManager.go @@ -0,0 +1,321 @@ +package creditManager + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/credit_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// CreditManager is the struct defined to group and contain all the methods +// that interact with the credit endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type CreditManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct CreditManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// Returns: +// - CreditManager: struct to interact with CreditManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *CreditManager { + + l.Trace.Printf("[CreditManager] Generating new CreditManager.\n") + + monit.InitEndpoint("credit") + + return &CreditManager{ + db: db, + monit: monit, + } + +} + +// AddConsumption (Swagger func) is the function behind the (POST) API Endpoint +// /credit/consumed/{id} +// Its job is to add a system consumption in the credit account provided the +// account ID. +func (m *CreditManager) AddConsumption(ctx context.Context, params credit_management.AddConsumptionParams) middleware.Responder { + + l.Trace.Printf("[CreditManager] AddConsumption endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("credit", time.Now()) + + creditStatus, e := m.db.AddConsumption(params.ID, params.Amount, params.Medium) + + if e != nil { + + s := "Problem adding the Comsumption: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewAddConsumptionInternalServerError().WithPayload(&errorReturn) + + } + + if creditStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewAddConsumptionOK().WithPayload(creditStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewAddConsumptionNotFound().WithPayload(&missingReturn) + +} + +// DecreaseCredit (Swagger func) is the function behind the (POST) API Endpoint +// /credit/available/decrease/{id} +// Its job is to decrease the amount of credit for an account in the system +// provided the account ID. +func (m *CreditManager) DecreaseCredit(ctx context.Context, params credit_management.DecreaseCreditParams) middleware.Responder { + + l.Trace.Printf("[CreditManager] DecreaseCredit endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("credit", time.Now()) + + creditStatus, e := m.db.DecreaseCredit(params.ID, params.Amount, params.Medium) + + if e != nil { + + s := "Problem decreassing the Credit: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewDecreaseCreditInternalServerError().WithPayload(&errorReturn) + + } + + if creditStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewDecreaseCreditOK().WithPayload(creditStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewDecreaseCreditNotFound().WithPayload(&missingReturn) + +} + +// GetCredit (Swagger func) is the function behind the (GET) API Endpoint +// /account/available/{id} +// Its job is to retrieve the amount of credit available fo an account in the +// system provided the account ID. +func (m *CreditManager) GetCredit(ctx context.Context, params credit_management.GetCreditParams) middleware.Responder { + + l.Trace.Printf("[CreditManager] GetCredit endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("credit", time.Now()) + + creditStatus, e := m.db.GetCredit(params.ID) + + if e != nil { + + s := "Problem getting the Credit Status: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewGetCreditInternalServerError().WithPayload(&errorReturn) + + } + + if creditStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewGetCreditOK().WithPayload(creditStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewGetCreditNotFound().WithPayload(&missingReturn) + +} + +// GetHistory (Swagger func) is the function behind the (GET) API Endpoint +// /credit/history/{id} +// Its job is to retrieve history of the credit balance for an account in the +// system provided the account ID. +func (m *CreditManager) GetHistory(ctx context.Context, params credit_management.GetHistoryParams) middleware.Responder { + + l.Trace.Printf("[CreditManager] GetHistory endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("credit", time.Now()) + + var filter bool + var medium string + + if params.FilterSystem != nil { + + filter = *params.FilterSystem + + } else { + + filter = false + + } + + if params.Medium != nil { + + medium = *params.Medium + + } + + creditStatus, e := m.db.GetHistory(params.ID, filter, medium) + + if e != nil { + + s := "Problem getting the Credit History: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewGetHistoryInternalServerError().WithPayload(&errorReturn) + + } + + if creditStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewGetHistoryOK().WithPayload(creditStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewGetHistoryNotFound().WithPayload(&missingReturn) + +} + +// IncreaseCredit (Swagger func) is the function behind the (POST) API Endpoint +// /credit/available/increase/{id} +// Its job is to increase the amount of credit for an account in the system +// provided the account ID. +func (m *CreditManager) IncreaseCredit(ctx context.Context, params credit_management.IncreaseCreditParams) middleware.Responder { + + l.Trace.Printf("[CreditManager] IncreaseCredit endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("credit", time.Now()) + + creditStatus, e := m.db.IncreaseCredit(params.ID, params.Amount, params.Medium) + + if e != nil { + + s := "Problem increassing the Credit: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusInternalServerError), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewIncreaseCreditInternalServerError().WithPayload(&errorReturn) + + } + + if creditStatus != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusOK), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewIncreaseCreditOK().WithPayload(creditStatus) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": fmt.Sprint(http.StatusNotFound), "method": params.HTTPRequest.Method, "route": params.HTTPRequest.URL.Path}).Inc() + + m.monit.APIHitDone("credit", callTime) + + return credit_management.NewIncreaseCreditNotFound().WithPayload(&missingReturn) + +} diff --git a/services/credit-system/server/dbManager/dbManager.go b/services/credit-system/server/dbManager/dbManager.go new file mode 100644 index 0000000..d6f1ece --- /dev/null +++ b/services/credit-system/server/dbManager/dbManager.go @@ -0,0 +1,854 @@ +package dbManager + +import ( + "encoding/json" + "errors" + "math" + "reflect" + "strings" + "time" + + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + cdrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/cacheManager" + cusModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + pmModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +const ( + scaler = 1e7 + statusDuplicated = iota + statusFail + statusMissing + statusOK + AC_CREDIT = "CREDIT" + AC_CASH = "CASH" + AC_BOTH = "BOTH" + AC_NONE = "NONE" + MED_CASH = "CASH" + MED_CREDIT = "CREDIT" +) + +var ( + //states = []string{"active", "error", "inactive", "suspended", "terminated"} + states = []string{"active", "error", "inactive", "used"} + totalTime float64 + totalCount int64 +) + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// On it there is the following parameters: +// - Cache: CacheManager pointer for the cache mechanism. +// - connStr: strings with the connection information to the database +// - Db: a gorm.DB pointer to the db to invoke all the db methods +type DbParameter struct { + Cache *cacheManager.CacheManager + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec +} + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization +// Returns: +// - DbParameter: struct to interact with dbManager functionalities¬ +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + } + + l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + dp.Db.AutoMigrate(tables...) + + //l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + //dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NewScope(&models.TABLE).TableName() + "', 'TIMESCALE-ROW-INDEX');") + + return &dp + +} + +// AddConsumption job is to decrease the credit in the system linked to the +// provided account by a certain amount of credit. +// This function is the one that produces a "cosumed" decrease of credit without +// human intervention. +// Parameters: +// - id: string containing the id of the account requested. +// - amount: float containing the amount to be -- in the system +// Returns: +// - reference to creditStatus containing the credit balance after the operation. +// - error raised in case of problems. +func (d *DbParameter) AddConsumption(id string, amount float64, medium string) (*models.CreditStatus, error) { + + l.Trace.Printf("[DB] Attempting to add a comsuption of %v credit, in the account with id: %v", amount, id) + + var c, c0, cs models.CreditStatus + var ce models.CreditEvents + var e error + + if r := d.Db.Where(&models.CreditStatus{AccountID: id}).First(&c).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Account with id: %v doesn't exist in the system, check with administrator.", id) + + e = errors.New("account doesn't exist in the system") + + } else { + + med := strings.ToUpper(medium) + + if med == models.CreditEventsMediumCREDIT { + + c0.AvailableCredit = c.AvailableCredit - amount + + } + + if med == models.CreditEventsMediumCASH { + + c0.AvailableCash = c.AvailableCash - amount + + } + + c0.LastUpdate = strfmt.DateTime(time.Now()) + + ce.AccountID = id + ce.Delta = -amount + ce.EventType = func(s string) *string { return &s }(models.EventEventTypeConsumption) + ce.Timestamp = strfmt.DateTime(time.Now()) + ce.Medium = &med + + if e = d.Db.Model(&c).Updates(c0).Error; e == nil { + + if e = d.Db.Create(&ce).Error; e == nil { + + d.Db.Where(&models.CreditStatus{AccountID: id}).First(&cs) + + } else { + + l.Trace.Printf("[DB] Attempting to add the comsuption of credit event for account in the system failed.") + + } + + } else { + + l.Trace.Printf("[DB] Attempting to update the account in the system failed.") + + } + + } + + return &cs, e + +} + +// CreateAccount job is to register a new account in the system with the provided +// ID. +// Parameters: +// - id: string containing the id of the account to be created. +// Returns: +// - reference to AccountStatus containing the state of the account after the +// operation. +// - error raised in case of problems. +func (d *DbParameter) CreateAccount(id string) (*models.AccountStatus, error) { + + l.Trace.Printf("[DB] Attempting to create a new account with id: %v", id) + + var a, a0, as models.AccountStatus + var c models.CreditStatus + var e error + + if r := d.Db.Where(&models.AccountStatus{AccountID: id}).First(&a).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + a0.AccountID = id + a0.CreatedAt = strfmt.DateTime(time.Now()) + + c.AccountID = id + c.LastUpdate = strfmt.DateTime(time.Now()) + + if e = d.Db.Create(&a0).Error; e == nil { + + if e = d.Db.Create(&c).Error; e == nil { + + d.Db.Where(&models.AccountStatus{AccountID: id}).First(&as) + + d.Metrics["count"].With(prometheus.Labels{"type": "Accounts created"}).Inc() + + } else { + + l.Trace.Printf("[DB] Attempting to create the credit account in the system failed.") + + } + + } else { + + l.Trace.Printf("[DB] Attempting to create the account in the system failed.") + + } + + } else { + + l.Trace.Printf("[DB] Account with id: %v already in the system, check with administrator.", id) + + e = errors.New("account already exist in the system") + + } + + return &as, e + +} + +// DecreaseCredit job is to decrease the credit in the system linked to the +// provided account by a certain amount of credit. +// Parameters: +// - id: string containing the id of the account requested. +// - amount: float containing the amount to be decreased in the system. +// Returns: +// - reference to CreditStatus containing the credit balance after the operation. +// - error raised in case of problems. +func (d *DbParameter) DecreaseCredit(id string, amount float64, medium string) (*models.CreditStatus, error) { + + l.Trace.Printf("[DB] Attempting to decrease credit by: %v, in the account with id: %v", amount, id) + + var c, c0, cs models.CreditStatus + var ce models.CreditEvents + var e error + + if r := d.Db.Where(&models.CreditStatus{AccountID: id}).First(&c).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Account with id: %v doesn't exist in the system, check with administrator.", id) + + e = errors.New("account doesn't exist in the system") + + } else { + + med := strings.ToUpper(medium) + + if med == models.CreditEventsMediumCREDIT { + + c0.AvailableCredit = c.AvailableCredit - amount + + } + + if med == models.CreditEventsMediumCASH { + + c0.AvailableCash = c.AvailableCash - amount + + } + + c0.LastUpdate = strfmt.DateTime(time.Now()) + + ce.AccountID = id + ce.Delta = -amount + ce.EventType = func(s string) *string { return &s }(models.EventEventTypeAuthorizedDecrease) + ce.Timestamp = strfmt.DateTime(time.Now()) + ce.Medium = &med + + if e = d.Db.Model(&c).Updates(c0).Error; e == nil { + + if e = d.Db.Create(&ce).Error; e == nil { + + d.Db.Where(&models.CreditStatus{AccountID: id}).First(&cs) + + } else { + + l.Trace.Printf("[DB] Attempting to add the decrease of credit event for account in the system failed.") + + } + + } else { + + l.Trace.Printf("[DB] Attempting to update the account in the system failed.") + + } + + } + + return &cs, e + +} + +// DisableAccount job is to mark as disabled in the system the account provided. +// Parameters: +// - id: string containing the id of the account to be disabled. +// Returns: +// - reference to AccountStatus containing the state of the account after the +// operation. +// - error raised in case of problems. +func (d *DbParameter) DisableAccount(id string) (*models.AccountStatus, error) { + + l.Trace.Printf("[DB] Attempting to disable account with id: %v", id) + + var a, as models.AccountStatus + var e error + + if r := d.Db.Where(&models.AccountStatus{AccountID: id}).First(&a).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Account with id: %v doesn't exist in the system, check with administrator.", id) + + e = errors.New("account doesn't exist in the system") + + } else { + + enabled := false + + if e = d.Db.Model(&a).Updates(&models.AccountStatus{Enabled: enabled}).Error; e == nil { + + d.Db.Where(&models.AccountStatus{AccountID: id}).First(&as) + + } else { + + l.Trace.Printf("[DB] Attempting to update the account in the system failed.") + + } + + } + + return &as, e + +} + +// EnableAccount job is to mark as enabled in the system the account provided. +// Parameters: +// - id: string containing the id of the account to be enabled. +// Returns: +// - reference to AccountStatus containing the state of the account after the +// operation. +// - error raised in case of problems. +func (d *DbParameter) EnableAccount(id string) (*models.AccountStatus, error) { + + l.Trace.Printf("[DB] Attempting to enable account with id: %v", id) + + var a, as models.AccountStatus + var e error + + if r := d.Db.Where(&models.AccountStatus{AccountID: id}).First(&a).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Account with id: %v doesn't exist in the system, check with administrator.", id) + + e = errors.New("account doesn't exist in the system") + + } else { + + if e = d.Db.Model(&a).Update("Enabled", true).Error; e == nil { + + d.Db.Where(&models.AccountStatus{AccountID: id}).First(&as) + + } else { + + l.Trace.Printf("[DB] Attempting to update the account in the system failed.") + + } + + } + + return &as, e + +} + +// GetAccountStatus job is to retrieve the actual state of the provided account. +// Parameters: +// - id: string containing the id of the account to be retrieved. +// Returns: +// - reference to AccountStatus containing the state of the account. +// - error raised in case of problems. +func (d *DbParameter) GetAccountStatus(id string) (*models.AccountStatus, error) { + + l.Trace.Printf("[DB] Attempting to get the status of the account with id: %v", id) + + var as models.AccountStatus + var e error + + if r := d.Db.Where(&models.AccountStatus{AccountID: id}).First(&as).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Account with id: %v doesn't exist in the system, check with administrator.", id) + + e = errors.New("account doesn't exist in the system") + + } + + return &as, e + +} + +// GetCredit job is to retrieve the actual state of the credit balance of the +// provided account. +// Parameters: +// - id: string containing the id of the account requested. +// Returns: +// - reference to CreditStatus containing the credit balance. +// - error raised in case of problems. +func (d *DbParameter) GetCredit(id string) (*models.CreditStatus, error) { + + l.Trace.Printf("[DB] Attempting to get the credit balance in the account with id: %v", id) + + var cs models.CreditStatus + var e error + + if r := d.Db.Where(&models.CreditStatus{AccountID: id}).First(&cs).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Account with id: %v doesn't exist in the system, check with administrator.", id) + + e = errors.New("account doesn't exist in the system") + + } + + return &cs, e + +} + +// GetHistory job is to retrieve the history of the credit balance of the account +// provided with the posibility of filter the actions. +// Parameters: +// - id: string containing the id of the account requested. +// - filtered: string specifying the criteria for filtering. +// Returns: +// - reference to CreditHistory containing the credit balance history contained +// in the system. +// - error raised in case of problems. +func (d *DbParameter) GetHistory(id string, filtered bool, medium string) (*models.CreditHistory, error) { + + l.Trace.Printf("[DB] Attempting to get the credit history in the account with id: %v", id) + + var ch models.CreditHistory + var ce []*models.CreditEvents + var e0 []*models.Event + var e error + + ch.AccountID = id + + med := strings.ToUpper(medium) + + if filtered { + + evType := models.EventEventTypeConsumption + + e = d.Db.Where(&models.CreditEvents{AccountID: id, Medium: &med}).Not(&models.CreditEvents{EventType: &evType}).Find(&ce).Error + + } else { + + e = d.Db.Where(&models.CreditEvents{AccountID: id, Medium: &med}).Find(&ce).Error + + } + + if e != nil { + + l.Trace.Printf("[DB] Account with id: %v doesn't have events in the system, check with administrator.", id) + + } + + for _, event := range ce { + + var ev models.Event + ev.Delta = event.Delta + ev.EventType = event.EventType + ev.Timestamp = event.Timestamp + ev.AuthorizedBy = event.AuthorizedBy + e0 = append(e0, &ev) + + } + + l.Trace.Printf("[DB] Amount of events for the account with id: %v, is: %v.", id, len(e0)) + + ch.Events = e0 + + return &ch, e + +} + +// IncreaseCredit job is to increase the credit in the system linked to the +// provided account by a certain amount of credit. +// Parameters: +// - id: string containing the id of the account requested. +// - amount: float containing the amount to be -- in the system +// Returns: +// - reference to CreditStatus containing the credit balance after the operation. +// - error raised in case of problems. +func (d *DbParameter) IncreaseCredit(id string, amount float64, medium string) (*models.CreditStatus, error) { + + l.Trace.Printf("[DB] Attempting to increase credit by: %v, in the account with id: %v", amount, id) + + var c, c0, cs models.CreditStatus + var ce models.CreditEvents + var e error + + if r := d.Db.Where(&models.CreditStatus{AccountID: id}).First(&c).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Account with id: %v doesn't exist in the system, check with administrator.", id) + + e = errors.New("account doesn't exist in the system") + + } else { + + med := strings.ToUpper(medium) + + if med == models.CreditEventsMediumCREDIT { + + c0.AvailableCredit = c.AvailableCredit + amount + + } + + if med == models.CreditEventsMediumCASH { + + c0.AvailableCash = c.AvailableCash + amount + + } + + c0.LastUpdate = strfmt.DateTime(time.Now()) + + ce.AccountID = id + ce.Delta = amount + ce.EventType = func(s string) *string { return &s }(models.EventEventTypeAuthorizedIncrease) + ce.Timestamp = strfmt.DateTime(time.Now()) + ce.Medium = &med + + if e = d.Db.Model(&c).Updates(c0).Error; e == nil { + + if e = d.Db.Create(&ce).Error; e == nil { + + d.Db.Where(&models.CreditStatus{AccountID: id}).First(&cs) + + } else { + + l.Trace.Printf("[DB] Attempting to add the increase of credit event for account in the system failed.") + + } + + } else { + + l.Trace.Printf("[DB] Attempting to update the account in the system failed.") + + } + + } + + return &cs, e + +} + +// ListAccounts job is to retrieve the list of all the accounts safe in the system. +// Returns: +// - slice of references to AccountStatus containing the status of every account +// in the system +func (d *DbParameter) ListAccounts() ([]*models.AccountStatus, error) { + + l.Trace.Printf("[DB] Attempting to list accounts in the system.") + + var as []*models.AccountStatus + var e error + + if e = d.Db.Find(&as).Error; e != nil { + + l.Trace.Printf("[DB] There is not accounts in the system") + + } + + return as, e + +} + +// ProcessCDR job is to check every CDR report arriving to the system to add the +// consumptions of each account to the corresponding +// Parameters: +// - report: CDR Report model reference to be processed. +// - usage: a boolean discriminant to set the accounting to usage instead of cost +// Returns: +// - e: error in case of problem while doing a conversion, a cache.get, or adding the comsumption. +func (d *DbParameter) ProcessCDR(report cdrModels.CReport, token string) error { + + l.Trace.Printf("[DB] Starting the processing of the a CDR.\n") + + var planID string + + now := time.Now().UnixNano() + + listAccounts, e := d.ListAccounts() + + if e != nil { + + l.Warning.Printf("[DB] There's was an error retrieving the accounts in the system. Error: %v\n", e) + + return e + + } + + if len(listAccounts) < 1 { + + l.Trace.Printf("[DB] There's no accounts in the system right now, skipping the processing...\n") + + return nil + + } + + p, e := d.Cache.Get(report.AccountID, "product", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the product info for id [ %v ]. Error: %v\n", report.AccountID, e) + + return e + + } + + product := p.(cusModels.Product) + + c, e := d.Cache.Get(product.CustomerID, "customer", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the customer info for id [ %v ]. Error: %v\n", product.CustomerID, e) + + return e + + } + + customer := c.(cusModels.Customer) + + account, e := d.GetAccountStatus(customer.CustomerID) + + if e != nil { + + l.Trace.Printf("[DB] There's no account associated in the customer level ID: [ %v ], moving to the next level...\n", customer.CustomerID) + + acc, e := d.GetAccountStatus(customer.ResellerID) + + if e != nil { + + l.Trace.Printf("[DB] There's no account associated in the reseller level. ID: [ %v ], skipping this product [ %v ].\n", customer.ResellerID, product.ProductID) + + return nil + + } + + account = acc + + } + + if !(account.Enabled) { + + l.Trace.Printf("[DB] Account associated [ %v ] is disabled! Skipping...\n", account.AccountID) + + return nil + + } + + if product.PlanID != "" { + + planID = product.PlanID + + } else { + + if customer.PlanID != "" { + + planID = customer.PlanID + + } else { + + r, e := d.Cache.Get(customer.ResellerID, "reseller", token) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the reseller info for id [ %v ]. Error: %v\n", customer.ResellerID, e) + + return e + + } + + reseller := r.(cusModels.Reseller) + + planID = reseller.PlanID + + } + + } + +PlanDefault: + p, e = d.Cache.Get(planID, "plan", token) + + if e != nil { + + if planID == "DEFAULT" { + + l.Warning.Printf("[DB] Something went wrong while retrieving the default plan id [ %v ]. Error: %v\n", planID, e) + + return e + + } + + l.Warning.Printf("[DB] Something went wrong while retrieving the plan id [ %v ]. Re-trying with default plan. Error: %v\n", planID, e) + + planID = "DEFAULT" + + goto PlanDefault + + } + + plan := p.(pmModels.Plan) + + // In case the plan is not valid we return to the deault plan (id 0) which is valid ad vitam + if (time.Now()).After((time.Time)(*plan.OfferedEndDate)) || (time.Now()).Before((time.Time)(*plan.OfferedStartDate)) { + + l.Warning.Printf("[DB] The plan [ %v ] is only valid between [ %v ] and [ %v ]. Falling back to default plan.\n", plan.ID, *plan.OfferedStartDate, *plan.OfferedEndDate) + + planID = "DEFAULT" + + goto PlanDefault + + } + + skus := make(map[string]*pmModels.SkuPrice) + + for _, k := range plan.SkuPrices { + + skus[k.SkuName] = k + + } + + var cashDelta, creditDelta float64 + + for i := range report.Usage { + + var value interface{} + + mode := *skus[report.Usage[i].ResourceType].AccountingMode + + if mode == AC_CREDIT || mode == AC_BOTH { + + for _, j := range states { + + value = report.Usage[i].UsageBreakup[j] + + if value == nil { + + l.Debug.Printf("[DB] The state [ %v ] seem to not be part of the usage UsageBreakup [ %+v ], skipping...", j, report.Usage[i].UsageBreakup) + + continue + + } + + if k := reflect.ValueOf(value); k.Kind() == reflect.Float64 { + + creditDelta += value.(float64) * skus[report.Usage[i].ResourceType].UnitCreditPrice + + continue + + } + + v, e := value.(json.Number).Float64() + + if e != nil { + + l.Warning.Printf("[DB] There was a problem retrieving the float value from the usagebreakup interface. Error: %v.\n", e) + + return e + + } + + creditDelta += v * skus[report.Usage[i].ResourceType].UnitCreditPrice + + } + + } + + if mode == AC_CASH || mode == AC_BOTH { + + value = report.Usage[i].Cost["totalFromSku"] + + if k := reflect.ValueOf(value); k.Kind() == reflect.Float64 { + + cashDelta += value.(float64) + + continue + + } + + v, e := value.(json.Number).Float64() + + if e != nil { + + l.Warning.Printf("[DB] There was a problem retrieving the float value from the cost interface. Error: %v.\n", e) + + return e + + } + + cashDelta += v + + } + + } + + state, e := d.AddConsumption(account.AccountID, d.getNiceFloat(creditDelta), MED_CREDIT) + + if e != nil { + + l.Warning.Printf("[DB] There was a problem while adding the consumption to the account [ %v ]. Error: %v.\n", account.AccountID, e) + + return e + } + + if state.AvailableCredit < float64(0) { + + l.Warning.Printf("[DB] Account [ %v ] credit is not positive. Credit: [ %v ].\n", account.AccountID, state.AvailableCredit) + + } + + l.Trace.Printf("[DB] Account [ %v ] has been updated with a [ %v ] consumption.\n", account.AccountID, creditDelta) + + state, e = d.AddConsumption(account.AccountID, d.getNiceFloat(cashDelta), MED_CASH) + + if e != nil { + + l.Warning.Printf("[DB] There was a problem while adding the consumption to the account [ %v ]. Error: %v.\n", account.AccountID, e) + + return e + } + + if state.AvailableCash < float64(0) { + + l.Warning.Printf("[DB] Account [ %v ] cash is not positive. Cash: [ %v ].\n", account.AccountID, state.AvailableCash) + + } + + l.Trace.Printf("[DB] Account [ %v ] has been updated with a [ %v ] consumption.\n", account.AccountID, cashDelta) + + totalTime += float64(time.Now().UnixNano()-now) / float64(time.Millisecond) + totalCount++ + + d.Metrics["count"].With(prometheus.Labels{"type": "CDRs procesed"}).Inc() + + d.Metrics["time"].With(prometheus.Labels{"type": "CDRs average processing time"}).Set(totalTime / float64(totalCount)) + + return nil + +} + +func (d *DbParameter) getNiceFloat(i float64) (o float64) { + + return float64(math.Round(i*scaler) / scaler) + +} diff --git a/services/credit-system/server/kafka.go b/services/credit-system/server/kafka.go new file mode 100644 index 0000000..39c80af --- /dev/null +++ b/services/credit-system/server/kafka.go @@ -0,0 +1,310 @@ +package main + +import ( + "context" + "crypto/tls" + "reflect" + "strconv" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/remeh/sizedwaitgroup" + "github.com/segmentio/encoding/json" + kafka "github.com/segmentio/kafka-go" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaFunction func(*dbManager.DbParameter, interface{}) error + +type kafkaHandlerConf struct { + in []kafkaPackage + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + model interface{} + function kafkaFunction + channel chan interface{} + saveDB bool +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(db *dbManager.DbParameter, monit *statusManager.StatusManager, kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.in != nil { + + monit.InitEndpoint("kafka-receiver") + + for _, p := range kH.in { + + go kafkaReceiver(db, monit, p.topic, p.partition, p.model, p.function, p.saveDB) + + } + } + + if kH.out != nil { + + monit.InitEndpoint("kafka-sender") + + for _, p := range kH.out { + + go kafkaSender(db, monit, p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaReceiver is the abstracted interface used to receive JSON data from kafka. +// The functions assumes that by default anything that comes from the kafka topic +// and validates against a specific data model has to be added to the db. +// Besides that it has the option to call an external function to interact with +// the data before putting it in the db. +// Parameters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - m: model to validate data against. +// - f: optional external function for more functionality. +// - saveDB: bool to control is the received data needs to be saved in the db. +func kafkaReceiver(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, m interface{}, f kafkaFunction, saveDB bool) { + + l.Trace.Printf("[KAFKA] Initializing kafka receiver for topic: %v.\n", t) + + conf := kafka.ReaderConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Partition: p, + MinBytes: cfg.Kafka.MinBytes, + MaxBytes: cfg.Kafka.MaxBytes, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + r := kafka.NewReader(conf) + defer r.Close() + + if e := r.SetOffset(cfg.Kafka.Offset); e != nil { + + l.Warning.Printf("[KAFKA] There was a problem when setting the offset, stopping the kafka handler NOW. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream offset"}).Inc() + + return + + } + + swg := sizedwaitgroup.New(8) + + for { + + rm, e := r.ReadMessage(context.Background()) + + if e != nil { + + l.Warning.Printf("[KAFKA] Error detected in the kafka stream. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream"}).Inc() + + continue + + } + + // Goroutines start + swg.Add() + go func() { + + callTime := time.Now() + monit.APIHit("kafka-receiver", callTime) + + defer swg.Done() + + o := reflect.New(reflect.TypeOf(m)).Interface() + + if e := json.Unmarshal(rm.Value, &o); e == nil { + + l.Info.Printf("[KAFKA] Relevant information detected in the stream: Topic: %v, partition: %v.\n", t, p) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object received"}).Inc() + + if f != nil { + + l.Info.Printf("[KAFKA] Function for specialized work detected. Starting its processing.\n") + + if err := f(db, o); err != nil { + + l.Warning.Printf("[KAFKA] There was a problem processing the model's specific function. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: linked function"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: linked function"}).Inc() + + } + + } + + if saveDB { + + l.Info.Printf("[KAFKA] Saving procesed record in the database.\n") + + if err := db.Db.Create(o).Error; err != nil { + + l.Warning.Printf("[KAFKA] There was a problem adding the record into the database. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: db saving"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object db saved"}).Inc() + + } + + } + + } else { + + l.Warning.Printf("[KAFKA] The information in the stream does not fit the expected model, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream-rubish"}).Inc() + + } + + monit.APIHitDone("kafka-receiver", callTime) + + }() + + } + +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + l.Info.Printf("[KAFKA] The channel has problems or has been closed.\n") + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: channel"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + callTime := time.Now() + monit.APIHit("kafka-sender", callTime) + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: stream"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "OK: object sent"}).Inc() + + } + + monit.APIHitDone("kafka-sender", callTime) + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: JSON Marshalling"}).Inc() + + } + + }() + + } + +} diff --git a/services/credit-system/server/main.go b/services/credit-system/server/main.go new file mode 100644 index 0000000..a47e810 --- /dev/null +++ b/services/credit-system/server/main.go @@ -0,0 +1,176 @@ +package main + +import ( + "crypto/tls" + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/services/credit-system/server/metrics.go b/services/credit-system/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/services/credit-system/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/services/credit-system/server/security.go b/services/credit-system/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/services/credit-system/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/services/credit-system/server/service.go b/services/credit-system/server/service.go new file mode 100644 index 0000000..4f00793 --- /dev/null +++ b/services/credit-system/server/service.go @@ -0,0 +1,135 @@ +package main + +import ( + "net/http" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + cdrModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/accountManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/creditManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,1,n have to be customized + db := dbStart(&models.AccountStatus{}, &models.CreditEvents{}, &models.CreditStatus{}) + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + // cache linked to the dbParameter + db.Cache = cacheStart(db.Metrics["cache"]) + + // In case of needed, here is where kafka support is started + // The functions needs to be customized accordingly to the needs of the service + // And the parts of the service that might need to send messages need to get + // the channel + _ = kafkaStart(db, mon) + + //bp := getBasePath() + + // Parts of the service HERE + a := accountManager.New(db, mon) + c := creditManager.New(db, mon) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + AccountManagementAPI: a, + CreditManagementAPI: c, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Parameters: +// - db: DbPAramenter reference for interaction with the db. +// - mon: statusManager parameter reference to interact with the statusManager +// subsystem +// Returns: +// - ch: a interface{} channel to be able to send thing through the kafka topic generated. +func kafkaStart(db *dbManager.DbParameter, mon *statusManager.StatusManager) (ch chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + f := func(db *dbManager.DbParameter, model interface{}) (e error) { + + if e = db.ProcessCDR(*model.(*cdrModels.CReport), ""); e != nil { + + l.Warning.Printf("[KAFKA] There was an error while apliying the linked function. Error: %v\n", e) + + } else { + + l.Trace.Printf("[KAFKA] Aplication of the linked function done succesfully.\n") + + } + + return + + } + + ch = make(chan interface{}) + + handler := kafkaHandlerConf{ + in: []kafkaPackage{ + { + topic: cfg.Kafka.TopicsIn[0], + model: cdrModels.CReport{}, + function: f, + saveDB: false, + }, + }, + } + + kafkaHandler(db, mon, handler) + + return + +} diff --git a/services/credit-system/server/statusManager/statusManager.go b/services/credit-system/server/statusManager/statusManager.go new file mode 100644 index 0000000..c921628 --- /dev/null +++ b/services/credit-system/server/statusManager/statusManager.go @@ -0,0 +1,325 @@ +package statusManager + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 + mutex *sync.Mutex +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + mutex = &sync.Mutex{} + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + avgTime[key] = t.UnixNano() + mutex.Unlock() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + previous, exists := avgTime[key] + mutex.Unlock() + + if exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + mutex.Lock() + delete(avgTime, key) + mutex.Unlock() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/services/credit-system/server/triggerManager/triggerManager.go b/services/credit-system/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..e6d8eee --- /dev/null +++ b/services/credit-system/server/triggerManager/triggerManager.go @@ -0,0 +1,72 @@ +package triggerManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/credit-system/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// TriggerManager is the struct defined to group and contain all the methods +// that interact with the trigger subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type TriggerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +var returnValue models.ErrorResponse + +// New is the function to create the struct TriggerManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// Returns: +// - TriggerManager: struct to interact with triggerManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *TriggerManager { + + l.Trace.Printf("[Trigger] Generating new triggerManager.\n") + + monit.InitEndpoint("trigger") + + // Default return string in case something weird happens. + // It usually means that something went wrong in the dbManager. + s := "Something unexpected happened, check with the administrator." + + returnValue = models.ErrorResponse{ + ErrorString: &s, + } + + return &TriggerManager{ + db: db, + monit: monit, + } + +} + +// ExecSample (Swagger func) is the function behind the /trigger/sample endpoint. +// It is a dummy function for reference. +func (m *TriggerManager) ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder { + + l.Trace.Printf("[Trigger] ExecSample endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/trigger/sample"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecSampleOK() + +} diff --git a/services/credit-system/swagger.yaml b/services/credit-system/swagger.yaml new file mode 100644 index 0000000..ca55645 --- /dev/null +++ b/services/credit-system/swagger.yaml @@ -0,0 +1,642 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v1.0" +info: + description: An API which supports creation, deletion, listing etc of Credit Manager + version: "1.0.0" + title: Credit Manager Management API + contact: + email: diego@cyclops-labs.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + - name: creditManagement + description: Actions relating to the control of the credits per account + - name: accountManagement + description: Actions relating to the account management in the service + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - kafka-receiver + - kafka-sender + - status + - trigger + - account + - credit + required: true + description: Id of the endpoint to be checked + /trigger/sample: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Sample task trigger + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: execSample + responses: + '200': + description: Sample task executed successfully + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + + /account/create/{id}: + get: + tags: + - accountManagement + produces: + - application/json + summary: Creates a new account in the system + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: createAccount + responses: + '201': + description: Account created, provided information of the new item created + schema: + $ref: "#/definitions/AccountStatus" + '409': + description: The account with the id provided already exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be created + + /account/disable/{id}: + post: + tags: + - accountManagement + consumes: + - application/json + produces: + - application/json + summary: Disables the account with the id provided in the system + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: disableAccount + responses: + '200': + description: Status information of the account with provided id in the system after the operation succeded + schema: + $ref: "#/definitions/AccountStatus" + '404': + description: The account with the id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be disabled + + /account/enable/{id}: + post: + tags: + - accountManagement + consumes: + - application/json + produces: + - application/json + summary: Enables the account with the id provided in the system + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: enableAccount + responses: + '200': + description: Status information of the account with provided id in the system after the operation succeded + schema: + $ref: "#/definitions/AccountStatus" + '404': + description: The account with the id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be enabled + + /account/list: + get: + tags: + - accountManagement + produces: + - application/json + summary: List of the accounts in the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: listAccounts + responses: + '200': + description: List of accounts in the system + schema: + type: array + items: + $ref: "#/definitions/AccountStatus" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + + /account/status/{id}: + get: + tags: + - accountManagement + produces: + - application/json + summary: Basic status of the account with the id provided in the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getAccountStatus + responses: + '200': + description: Status information of the account with provided id in the system + schema: + $ref: "#/definitions/AccountStatus" + '404': + description: The account with the id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be checked + + /account/available/{id}: + get: + tags: + - creditManagement + produces: + - application/json + summary: Credit status of the account with the provided id + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getCredit + responses: + '200': + description: Credit status of the account with the provided id + schema: + $ref: "#/definitions/CreditStatus" + '404': + description: The account with the provided id doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be checked + + /{medium}/available/decrease/{id}: + post: + tags: + - creditManagement + consumes: + - application/json + produces: + - application/json + summary: Insert a new reseller in the system. + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: decreaseCredit + responses: + '200': + description: Credit status of the account with the provided id + schema: + $ref: "#/definitions/CreditStatus" + '404': + description: The account with the id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be checked + - name: amount + in: query + description: Amount to be decreased + required: true + type: number + format: double + - name: medium + in: path + description: Medium (cash/credit) to be used in the accounting + required: true + type: string + enum: + - credit + - cash + + /{medium}/available/increase/{id}: + post: + tags: + - creditManagement + consumes: + - application/json + produces: + - application/json + summary: Insert a new reseller in the system. + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: increaseCredit + responses: + '200': + description: Credit status of the account with the provided id + schema: + $ref: "#/definitions/CreditStatus" + '404': + description: The account with the id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be checked + - name: amount + in: query + description: Amount to be inccreased + required: true + type: number + format: double + - name: medium + in: path + description: Medium (cash/credit) to be used in the accounting + required: true + type: string + enum: + - credit + - cash + + /{medium}/consume/{id}: + post: + tags: + - creditManagement + consumes: + - application/json + produces: + - application/json + summary: Adds a consumption to the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: addConsumption + responses: + '200': + description: Credit status of the account with the provided id + schema: + $ref: "#/definitions/CreditStatus" + '404': + description: The account with the id provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to be checked + - name: amount + in: query + description: Amount to be decreased + required: true + type: number + format: double + - name: medium + in: path + description: Medium (cash/credit) to be used in the accounting + required: true + type: string + enum: + - credit + - cash + + /history/{id}: + get: + tags: + - creditManagement + produces: + - application/json + summary: Credit history of the customer with id + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getHistory + responses: + '200': + description: Credit status history of the account with the provided id + schema: + $ref: "#/definitions/CreditHistory" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the account to get the history + - name: filterSystem + in: query + type: boolean + description: Boolean variable to control if the system consumptions have to be listed or not + - name: medium + in: query + description: Medium (cash/credit) to be used as filter + type: string + enum: + - credit + - cash + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + + AccountStatus: + type: object + required: + - Enabled + properties: + AccountID: + type: string + x-go-custom-tag: gorm:"primary_key" + CreatedAt: + type: string + format: datetime + x-go-custom-tag: gorm:"type:timestamptz" + Enabled: + type: boolean + x-go-custom-tag: gorm:"default:true" + default: true + + CreditEvents: + type: object + properties: + AccountId: + type: string + x-go-custom-tag: gorm:"index" + AuthorizedBy: + type: string + Delta: + type: number + format: double + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + EventType: + type: string + x-go-custom-tag: gorm:"index;default:Consumption" + default: Consumption + enum: + - AuthorizedIncrease + - AuthorizedDecrease + - Consumption + - AutomaticCreditExpiry + - Refund + ID: + type: integer + x-go-custom-tag: gorm:"primary_key" + Timestamp: + type: string + format: datetime + x-go-custom-tag: gorm:"type:timestamptz" + Medium: + type: string + x-go-custom-tag: gorm:"index;default:CREDIT" + default: CREDIT + enum: + - CREDIT + - CASH + + CreditHistory: + type: object + properties: + AccountID: + type: string + x-go-custom-tag: gorm:"primary_key" + Events: + type: array + items: + $ref: '#/definitions/Event' + + CreditStatus: + type: object + properties: + AccountID: + type: string + x-go-custom-tag: gorm:"primary_key" + AvailableCredit: + type: number + format: double + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + AvailableCash: + type: number + format: double + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + LastUpdate: + type: string + format: datetime + x-go-custom-tag: gorm:"type:timestamptz" + + Event: + type: object + properties: + AuthorizedBy: + type: string + Delta: + type: number + format: double + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + EventType: + type: string + x-go-custom-tag: gorm:"index;default:Consumption" + default: Consumption + enum: + - AuthorizedIncrease + - AuthorizedDecrease + - Consumption + - AutomaticCreditExpiry + - Refund + Timestamp: + type: string + format: datetime + x-go-custom-tag: gorm:"type:timestamptz" + Medium: + type: string + x-go-custom-tag: gorm:"index;default:CREDIT" + default: CREDIT + enum: + - CREDIT + - CASH + diff --git a/services/customerdb/README.md b/services/customerdb/README.md new file mode 100644 index 0000000..ef6afb9 --- /dev/null +++ b/services/customerdb/README.md @@ -0,0 +1,26 @@ +# CUSTOMER DATABASE SERVICE + +Cyclops Engine's Customer Database Service implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + diff --git a/services/customerdb/client/customer_database_management_client.go b/services/customerdb/client/customer_database_management_client.go new file mode 100644 index 0000000..3b12d68 --- /dev/null +++ b/services/customerdb/client/customer_database_management_client.go @@ -0,0 +1,81 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/customer_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/product_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/reseller_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/trigger_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v1.0" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new customer database management HTTP client. +func New(c Config) *CustomerDatabaseManagement { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(CustomerDatabaseManagement) + cli.Transport = transport + cli.CustomerManagement = customer_management.New(transport, strfmt.Default, c.AuthInfo) + cli.ProductManagement = product_management.New(transport, strfmt.Default, c.AuthInfo) + cli.ResellerManagement = reseller_management.New(transport, strfmt.Default, c.AuthInfo) + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// CustomerDatabaseManagement is a client for customer database management +type CustomerDatabaseManagement struct { + CustomerManagement *customer_management.Client + ProductManagement *product_management.Client + ResellerManagement *reseller_management.Client + StatusManagement *status_management.Client + TriggerManagement *trigger_management.Client + Transport runtime.ClientTransport +} diff --git a/services/customerdb/client/customer_management/add_customer_parameters.go b/services/customerdb/client/customer_management/add_customer_parameters.go new file mode 100644 index 0000000..78bccc0 --- /dev/null +++ b/services/customerdb/client/customer_management/add_customer_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewAddCustomerParams creates a new AddCustomerParams object +// with the default values initialized. +func NewAddCustomerParams() *AddCustomerParams { + var () + return &AddCustomerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewAddCustomerParamsWithTimeout creates a new AddCustomerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewAddCustomerParamsWithTimeout(timeout time.Duration) *AddCustomerParams { + var () + return &AddCustomerParams{ + + timeout: timeout, + } +} + +// NewAddCustomerParamsWithContext creates a new AddCustomerParams object +// with the default values initialized, and the ability to set a context for a request +func NewAddCustomerParamsWithContext(ctx context.Context) *AddCustomerParams { + var () + return &AddCustomerParams{ + + Context: ctx, + } +} + +// NewAddCustomerParamsWithHTTPClient creates a new AddCustomerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewAddCustomerParamsWithHTTPClient(client *http.Client) *AddCustomerParams { + var () + return &AddCustomerParams{ + HTTPClient: client, + } +} + +/*AddCustomerParams contains all the parameters to send to the API endpoint +for the add customer operation typically these are written to a http.Request +*/ +type AddCustomerParams struct { + + /*Customer + Customer to be added + + */ + Customer *models.Customer + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the add customer params +func (o *AddCustomerParams) WithTimeout(timeout time.Duration) *AddCustomerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add customer params +func (o *AddCustomerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add customer params +func (o *AddCustomerParams) WithContext(ctx context.Context) *AddCustomerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add customer params +func (o *AddCustomerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add customer params +func (o *AddCustomerParams) WithHTTPClient(client *http.Client) *AddCustomerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add customer params +func (o *AddCustomerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCustomer adds the customer to the add customer params +func (o *AddCustomerParams) WithCustomer(customer *models.Customer) *AddCustomerParams { + o.SetCustomer(customer) + return o +} + +// SetCustomer adds the customer to the add customer params +func (o *AddCustomerParams) SetCustomer(customer *models.Customer) { + o.Customer = customer +} + +// WriteToRequest writes these params to a swagger request +func (o *AddCustomerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Customer != nil { + if err := r.SetBodyParam(o.Customer); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/customer_management/add_customer_responses.go b/services/customerdb/client/customer_management/add_customer_responses.go new file mode 100644 index 0000000..117c0d6 --- /dev/null +++ b/services/customerdb/client/customer_management/add_customer_responses.go @@ -0,0 +1,213 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// AddCustomerReader is a Reader for the AddCustomer structure. +type AddCustomerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddCustomerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewAddCustomerCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 202: + result := NewAddCustomerAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewAddCustomerBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewAddCustomerConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewAddCustomerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewAddCustomerCreated creates a AddCustomerCreated with default headers values +func NewAddCustomerCreated() *AddCustomerCreated { + return &AddCustomerCreated{} +} + +/*AddCustomerCreated handles this case with default header values. + +New customer was added successfully +*/ +type AddCustomerCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *AddCustomerCreated) Error() string { + return fmt.Sprintf("[POST /customer][%d] addCustomerCreated %+v", 201, o.Payload) +} + +func (o *AddCustomerCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *AddCustomerCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddCustomerAccepted creates a AddCustomerAccepted with default headers values +func NewAddCustomerAccepted() *AddCustomerAccepted { + return &AddCustomerAccepted{} +} + +/*AddCustomerAccepted handles this case with default header values. + +The new customer was added but there might have been some fails when adding part of the data +*/ +type AddCustomerAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *AddCustomerAccepted) Error() string { + return fmt.Sprintf("[POST /customer][%d] addCustomerAccepted %+v", 202, o.Payload) +} + +func (o *AddCustomerAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *AddCustomerAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddCustomerBadRequest creates a AddCustomerBadRequest with default headers values +func NewAddCustomerBadRequest() *AddCustomerBadRequest { + return &AddCustomerBadRequest{} +} + +/*AddCustomerBadRequest handles this case with default header values. + +Invalid input, object invalid +*/ +type AddCustomerBadRequest struct { +} + +func (o *AddCustomerBadRequest) Error() string { + return fmt.Sprintf("[POST /customer][%d] addCustomerBadRequest ", 400) +} + +func (o *AddCustomerBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewAddCustomerConflict creates a AddCustomerConflict with default headers values +func NewAddCustomerConflict() *AddCustomerConflict { + return &AddCustomerConflict{} +} + +/*AddCustomerConflict handles this case with default header values. + +The given item already exists +*/ +type AddCustomerConflict struct { + Payload *models.ErrorResponse +} + +func (o *AddCustomerConflict) Error() string { + return fmt.Sprintf("[POST /customer][%d] addCustomerConflict %+v", 409, o.Payload) +} + +func (o *AddCustomerConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddCustomerConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddCustomerInternalServerError creates a AddCustomerInternalServerError with default headers values +func NewAddCustomerInternalServerError() *AddCustomerInternalServerError { + return &AddCustomerInternalServerError{} +} + +/*AddCustomerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type AddCustomerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *AddCustomerInternalServerError) Error() string { + return fmt.Sprintf("[POST /customer][%d] addCustomerInternalServerError %+v", 500, o.Payload) +} + +func (o *AddCustomerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddCustomerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/customer_management/customer_management_client.go b/services/customerdb/client/customer_management/customer_management_client.go new file mode 100644 index 0000000..b923489 --- /dev/null +++ b/services/customerdb/client/customer_management/customer_management_client.go @@ -0,0 +1,162 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the customer management client +type API interface { + /* + AddCustomer inserts a new customer in the system*/ + AddCustomer(ctx context.Context, params *AddCustomerParams) (*AddCustomerCreated, *AddCustomerAccepted, error) + /* + GetCustomer returns the information about the customer with the given id*/ + GetCustomer(ctx context.Context, params *GetCustomerParams) (*GetCustomerOK, error) + /* + ListCustomers lists all the customers in the system*/ + ListCustomers(ctx context.Context, params *ListCustomersParams) (*ListCustomersOK, error) + /* + UpdateCustomer updates the information of the customer with the given id*/ + UpdateCustomer(ctx context.Context, params *UpdateCustomerParams) (*UpdateCustomerOK, *UpdateCustomerAccepted, error) +} + +// New creates a new customer management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for customer management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +AddCustomer inserts a new customer in the system +*/ +func (a *Client) AddCustomer(ctx context.Context, params *AddCustomerParams) (*AddCustomerCreated, *AddCustomerAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "addCustomer", + Method: "POST", + PathPattern: "/customer", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &AddCustomerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, nil, err + } + switch value := result.(type) { + case *AddCustomerCreated: + return value, nil, nil + case *AddCustomerAccepted: + return nil, value, nil + } + return nil, nil, nil + +} + +/* +GetCustomer returns the information about the customer with the given id +*/ +func (a *Client) GetCustomer(ctx context.Context, params *GetCustomerParams) (*GetCustomerOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getCustomer", + Method: "GET", + PathPattern: "/customer/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetCustomerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetCustomerOK), nil + +} + +/* +ListCustomers lists all the customers in the system +*/ +func (a *Client) ListCustomers(ctx context.Context, params *ListCustomersParams) (*ListCustomersOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listCustomers", + Method: "GET", + PathPattern: "/customer", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListCustomersReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListCustomersOK), nil + +} + +/* +UpdateCustomer updates the information of the customer with the given id +*/ +func (a *Client) UpdateCustomer(ctx context.Context, params *UpdateCustomerParams) (*UpdateCustomerOK, *UpdateCustomerAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updateCustomer", + Method: "PUT", + PathPattern: "/customer/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdateCustomerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, nil, err + } + switch value := result.(type) { + case *UpdateCustomerOK: + return value, nil, nil + case *UpdateCustomerAccepted: + return nil, value, nil + } + return nil, nil, nil + +} diff --git a/services/customerdb/client/customer_management/get_customer_parameters.go b/services/customerdb/client/customer_management/get_customer_parameters.go new file mode 100644 index 0000000..2554745 --- /dev/null +++ b/services/customerdb/client/customer_management/get_customer_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCustomerParams creates a new GetCustomerParams object +// with the default values initialized. +func NewGetCustomerParams() *GetCustomerParams { + var () + return &GetCustomerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetCustomerParamsWithTimeout creates a new GetCustomerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetCustomerParamsWithTimeout(timeout time.Duration) *GetCustomerParams { + var () + return &GetCustomerParams{ + + timeout: timeout, + } +} + +// NewGetCustomerParamsWithContext creates a new GetCustomerParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetCustomerParamsWithContext(ctx context.Context) *GetCustomerParams { + var () + return &GetCustomerParams{ + + Context: ctx, + } +} + +// NewGetCustomerParamsWithHTTPClient creates a new GetCustomerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetCustomerParamsWithHTTPClient(client *http.Client) *GetCustomerParams { + var () + return &GetCustomerParams{ + HTTPClient: client, + } +} + +/*GetCustomerParams contains all the parameters to send to the API endpoint +for the get customer operation typically these are written to a http.Request +*/ +type GetCustomerParams struct { + + /*ID + Id of the customer to be retrieved + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get customer params +func (o *GetCustomerParams) WithTimeout(timeout time.Duration) *GetCustomerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get customer params +func (o *GetCustomerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get customer params +func (o *GetCustomerParams) WithContext(ctx context.Context) *GetCustomerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get customer params +func (o *GetCustomerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get customer params +func (o *GetCustomerParams) WithHTTPClient(client *http.Client) *GetCustomerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get customer params +func (o *GetCustomerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get customer params +func (o *GetCustomerParams) WithID(id string) *GetCustomerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get customer params +func (o *GetCustomerParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCustomerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/customer_management/get_customer_responses.go b/services/customerdb/client/customer_management/get_customer_responses.go new file mode 100644 index 0000000..c063c6a --- /dev/null +++ b/services/customerdb/client/customer_management/get_customer_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetCustomerReader is a Reader for the GetCustomer structure. +type GetCustomerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCustomerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCustomerOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetCustomerNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetCustomerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetCustomerOK creates a GetCustomerOK with default headers values +func NewGetCustomerOK() *GetCustomerOK { + return &GetCustomerOK{} +} + +/*GetCustomerOK handles this case with default header values. + +Customer with the id given in the system returned +*/ +type GetCustomerOK struct { + Payload *models.Customer +} + +func (o *GetCustomerOK) Error() string { + return fmt.Sprintf("[GET /customer/{id}][%d] getCustomerOK %+v", 200, o.Payload) +} + +func (o *GetCustomerOK) GetPayload() *models.Customer { + return o.Payload +} + +func (o *GetCustomerOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Customer) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCustomerNotFound creates a GetCustomerNotFound with default headers values +func NewGetCustomerNotFound() *GetCustomerNotFound { + return &GetCustomerNotFound{} +} + +/*GetCustomerNotFound handles this case with default header values. + +The customer with the given id wasn't found +*/ +type GetCustomerNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetCustomerNotFound) Error() string { + return fmt.Sprintf("[GET /customer/{id}][%d] getCustomerNotFound %+v", 404, o.Payload) +} + +func (o *GetCustomerNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCustomerNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCustomerInternalServerError creates a GetCustomerInternalServerError with default headers values +func NewGetCustomerInternalServerError() *GetCustomerInternalServerError { + return &GetCustomerInternalServerError{} +} + +/*GetCustomerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetCustomerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetCustomerInternalServerError) Error() string { + return fmt.Sprintf("[GET /customer/{id}][%d] getCustomerInternalServerError %+v", 500, o.Payload) +} + +func (o *GetCustomerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCustomerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/customer_management/list_customers_parameters.go b/services/customerdb/client/customer_management/list_customers_parameters.go new file mode 100644 index 0000000..502f0ce --- /dev/null +++ b/services/customerdb/client/customer_management/list_customers_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListCustomersParams creates a new ListCustomersParams object +// with the default values initialized. +func NewListCustomersParams() *ListCustomersParams { + + return &ListCustomersParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListCustomersParamsWithTimeout creates a new ListCustomersParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListCustomersParamsWithTimeout(timeout time.Duration) *ListCustomersParams { + + return &ListCustomersParams{ + + timeout: timeout, + } +} + +// NewListCustomersParamsWithContext creates a new ListCustomersParams object +// with the default values initialized, and the ability to set a context for a request +func NewListCustomersParamsWithContext(ctx context.Context) *ListCustomersParams { + + return &ListCustomersParams{ + + Context: ctx, + } +} + +// NewListCustomersParamsWithHTTPClient creates a new ListCustomersParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListCustomersParamsWithHTTPClient(client *http.Client) *ListCustomersParams { + + return &ListCustomersParams{ + HTTPClient: client, + } +} + +/*ListCustomersParams contains all the parameters to send to the API endpoint +for the list customers operation typically these are written to a http.Request +*/ +type ListCustomersParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list customers params +func (o *ListCustomersParams) WithTimeout(timeout time.Duration) *ListCustomersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list customers params +func (o *ListCustomersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list customers params +func (o *ListCustomersParams) WithContext(ctx context.Context) *ListCustomersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list customers params +func (o *ListCustomersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list customers params +func (o *ListCustomersParams) WithHTTPClient(client *http.Client) *ListCustomersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list customers params +func (o *ListCustomersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListCustomersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/customer_management/list_customers_responses.go b/services/customerdb/client/customer_management/list_customers_responses.go new file mode 100644 index 0000000..8ae7536 --- /dev/null +++ b/services/customerdb/client/customer_management/list_customers_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ListCustomersReader is a Reader for the ListCustomers structure. +type ListCustomersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListCustomersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListCustomersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListCustomersInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewListCustomersOK creates a ListCustomersOK with default headers values +func NewListCustomersOK() *ListCustomersOK { + return &ListCustomersOK{} +} + +/*ListCustomersOK handles this case with default header values. + +List of customers in the system returned +*/ +type ListCustomersOK struct { + Payload []*models.Customer +} + +func (o *ListCustomersOK) Error() string { + return fmt.Sprintf("[GET /customer][%d] listCustomersOK %+v", 200, o.Payload) +} + +func (o *ListCustomersOK) GetPayload() []*models.Customer { + return o.Payload +} + +func (o *ListCustomersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListCustomersInternalServerError creates a ListCustomersInternalServerError with default headers values +func NewListCustomersInternalServerError() *ListCustomersInternalServerError { + return &ListCustomersInternalServerError{} +} + +/*ListCustomersInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListCustomersInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListCustomersInternalServerError) Error() string { + return fmt.Sprintf("[GET /customer][%d] listCustomersInternalServerError %+v", 500, o.Payload) +} + +func (o *ListCustomersInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListCustomersInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/customer_management/update_customer_parameters.go b/services/customerdb/client/customer_management/update_customer_parameters.go new file mode 100644 index 0000000..8c1cbf4 --- /dev/null +++ b/services/customerdb/client/customer_management/update_customer_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewUpdateCustomerParams creates a new UpdateCustomerParams object +// with the default values initialized. +func NewUpdateCustomerParams() *UpdateCustomerParams { + var () + return &UpdateCustomerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateCustomerParamsWithTimeout creates a new UpdateCustomerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdateCustomerParamsWithTimeout(timeout time.Duration) *UpdateCustomerParams { + var () + return &UpdateCustomerParams{ + + timeout: timeout, + } +} + +// NewUpdateCustomerParamsWithContext creates a new UpdateCustomerParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdateCustomerParamsWithContext(ctx context.Context) *UpdateCustomerParams { + var () + return &UpdateCustomerParams{ + + Context: ctx, + } +} + +// NewUpdateCustomerParamsWithHTTPClient creates a new UpdateCustomerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdateCustomerParamsWithHTTPClient(client *http.Client) *UpdateCustomerParams { + var () + return &UpdateCustomerParams{ + HTTPClient: client, + } +} + +/*UpdateCustomerParams contains all the parameters to send to the API endpoint +for the update customer operation typically these are written to a http.Request +*/ +type UpdateCustomerParams struct { + + /*Customer + Customer to be updated + + */ + Customer *models.Customer + /*ID + Id of the customer to be updated + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update customer params +func (o *UpdateCustomerParams) WithTimeout(timeout time.Duration) *UpdateCustomerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update customer params +func (o *UpdateCustomerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update customer params +func (o *UpdateCustomerParams) WithContext(ctx context.Context) *UpdateCustomerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update customer params +func (o *UpdateCustomerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update customer params +func (o *UpdateCustomerParams) WithHTTPClient(client *http.Client) *UpdateCustomerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update customer params +func (o *UpdateCustomerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCustomer adds the customer to the update customer params +func (o *UpdateCustomerParams) WithCustomer(customer *models.Customer) *UpdateCustomerParams { + o.SetCustomer(customer) + return o +} + +// SetCustomer adds the customer to the update customer params +func (o *UpdateCustomerParams) SetCustomer(customer *models.Customer) { + o.Customer = customer +} + +// WithID adds the id to the update customer params +func (o *UpdateCustomerParams) WithID(id string) *UpdateCustomerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update customer params +func (o *UpdateCustomerParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateCustomerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Customer != nil { + if err := r.SetBodyParam(o.Customer); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/customer_management/update_customer_responses.go b/services/customerdb/client/customer_management/update_customer_responses.go new file mode 100644 index 0000000..09d642e --- /dev/null +++ b/services/customerdb/client/customer_management/update_customer_responses.go @@ -0,0 +1,186 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// UpdateCustomerReader is a Reader for the UpdateCustomer structure. +type UpdateCustomerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateCustomerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateCustomerOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 202: + result := NewUpdateCustomerAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdateCustomerNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdateCustomerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewUpdateCustomerOK creates a UpdateCustomerOK with default headers values +func NewUpdateCustomerOK() *UpdateCustomerOK { + return &UpdateCustomerOK{} +} + +/*UpdateCustomerOK handles this case with default header values. + +Customer with the given id was updated +*/ +type UpdateCustomerOK struct { + Payload *models.ItemCreatedResponse +} + +func (o *UpdateCustomerOK) Error() string { + return fmt.Sprintf("[PUT /customer/{id}][%d] updateCustomerOK %+v", 200, o.Payload) +} + +func (o *UpdateCustomerOK) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *UpdateCustomerOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateCustomerAccepted creates a UpdateCustomerAccepted with default headers values +func NewUpdateCustomerAccepted() *UpdateCustomerAccepted { + return &UpdateCustomerAccepted{} +} + +/*UpdateCustomerAccepted handles this case with default header values. + +The customer was updated but there might have been some fails when adding part of the data +*/ +type UpdateCustomerAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *UpdateCustomerAccepted) Error() string { + return fmt.Sprintf("[PUT /customer/{id}][%d] updateCustomerAccepted %+v", 202, o.Payload) +} + +func (o *UpdateCustomerAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *UpdateCustomerAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateCustomerNotFound creates a UpdateCustomerNotFound with default headers values +func NewUpdateCustomerNotFound() *UpdateCustomerNotFound { + return &UpdateCustomerNotFound{} +} + +/*UpdateCustomerNotFound handles this case with default header values. + +The customer with the given id wasn't found +*/ +type UpdateCustomerNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdateCustomerNotFound) Error() string { + return fmt.Sprintf("[PUT /customer/{id}][%d] updateCustomerNotFound %+v", 404, o.Payload) +} + +func (o *UpdateCustomerNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateCustomerNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateCustomerInternalServerError creates a UpdateCustomerInternalServerError with default headers values +func NewUpdateCustomerInternalServerError() *UpdateCustomerInternalServerError { + return &UpdateCustomerInternalServerError{} +} + +/*UpdateCustomerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type UpdateCustomerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdateCustomerInternalServerError) Error() string { + return fmt.Sprintf("[PUT /customer/{id}][%d] updateCustomerInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdateCustomerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateCustomerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/product_management/add_product_parameters.go b/services/customerdb/client/product_management/add_product_parameters.go new file mode 100644 index 0000000..e7f007f --- /dev/null +++ b/services/customerdb/client/product_management/add_product_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewAddProductParams creates a new AddProductParams object +// with the default values initialized. +func NewAddProductParams() *AddProductParams { + var () + return &AddProductParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewAddProductParamsWithTimeout creates a new AddProductParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewAddProductParamsWithTimeout(timeout time.Duration) *AddProductParams { + var () + return &AddProductParams{ + + timeout: timeout, + } +} + +// NewAddProductParamsWithContext creates a new AddProductParams object +// with the default values initialized, and the ability to set a context for a request +func NewAddProductParamsWithContext(ctx context.Context) *AddProductParams { + var () + return &AddProductParams{ + + Context: ctx, + } +} + +// NewAddProductParamsWithHTTPClient creates a new AddProductParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewAddProductParamsWithHTTPClient(client *http.Client) *AddProductParams { + var () + return &AddProductParams{ + HTTPClient: client, + } +} + +/*AddProductParams contains all the parameters to send to the API endpoint +for the add product operation typically these are written to a http.Request +*/ +type AddProductParams struct { + + /*Product + Product to be added + + */ + Product *models.Product + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the add product params +func (o *AddProductParams) WithTimeout(timeout time.Duration) *AddProductParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add product params +func (o *AddProductParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add product params +func (o *AddProductParams) WithContext(ctx context.Context) *AddProductParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add product params +func (o *AddProductParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add product params +func (o *AddProductParams) WithHTTPClient(client *http.Client) *AddProductParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add product params +func (o *AddProductParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithProduct adds the product to the add product params +func (o *AddProductParams) WithProduct(product *models.Product) *AddProductParams { + o.SetProduct(product) + return o +} + +// SetProduct adds the product to the add product params +func (o *AddProductParams) SetProduct(product *models.Product) { + o.Product = product +} + +// WriteToRequest writes these params to a swagger request +func (o *AddProductParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Product != nil { + if err := r.SetBodyParam(o.Product); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/product_management/add_product_responses.go b/services/customerdb/client/product_management/add_product_responses.go new file mode 100644 index 0000000..a2190e0 --- /dev/null +++ b/services/customerdb/client/product_management/add_product_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// AddProductReader is a Reader for the AddProduct structure. +type AddProductReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddProductReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewAddProductCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewAddProductBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewAddProductConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewAddProductInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewAddProductCreated creates a AddProductCreated with default headers values +func NewAddProductCreated() *AddProductCreated { + return &AddProductCreated{} +} + +/*AddProductCreated handles this case with default header values. + +New product was added successfully +*/ +type AddProductCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *AddProductCreated) Error() string { + return fmt.Sprintf("[POST /product][%d] addProductCreated %+v", 201, o.Payload) +} + +func (o *AddProductCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *AddProductCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddProductBadRequest creates a AddProductBadRequest with default headers values +func NewAddProductBadRequest() *AddProductBadRequest { + return &AddProductBadRequest{} +} + +/*AddProductBadRequest handles this case with default header values. + +Invalid input, object invalid +*/ +type AddProductBadRequest struct { +} + +func (o *AddProductBadRequest) Error() string { + return fmt.Sprintf("[POST /product][%d] addProductBadRequest ", 400) +} + +func (o *AddProductBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewAddProductConflict creates a AddProductConflict with default headers values +func NewAddProductConflict() *AddProductConflict { + return &AddProductConflict{} +} + +/*AddProductConflict handles this case with default header values. + +The given item already exists +*/ +type AddProductConflict struct { + Payload *models.ErrorResponse +} + +func (o *AddProductConflict) Error() string { + return fmt.Sprintf("[POST /product][%d] addProductConflict %+v", 409, o.Payload) +} + +func (o *AddProductConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddProductConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddProductInternalServerError creates a AddProductInternalServerError with default headers values +func NewAddProductInternalServerError() *AddProductInternalServerError { + return &AddProductInternalServerError{} +} + +/*AddProductInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type AddProductInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *AddProductInternalServerError) Error() string { + return fmt.Sprintf("[POST /product][%d] addProductInternalServerError %+v", 500, o.Payload) +} + +func (o *AddProductInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddProductInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/product_management/get_product_parameters.go b/services/customerdb/client/product_management/get_product_parameters.go new file mode 100644 index 0000000..37b4454 --- /dev/null +++ b/services/customerdb/client/product_management/get_product_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetProductParams creates a new GetProductParams object +// with the default values initialized. +func NewGetProductParams() *GetProductParams { + var () + return &GetProductParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetProductParamsWithTimeout creates a new GetProductParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetProductParamsWithTimeout(timeout time.Duration) *GetProductParams { + var () + return &GetProductParams{ + + timeout: timeout, + } +} + +// NewGetProductParamsWithContext creates a new GetProductParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetProductParamsWithContext(ctx context.Context) *GetProductParams { + var () + return &GetProductParams{ + + Context: ctx, + } +} + +// NewGetProductParamsWithHTTPClient creates a new GetProductParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetProductParamsWithHTTPClient(client *http.Client) *GetProductParams { + var () + return &GetProductParams{ + HTTPClient: client, + } +} + +/*GetProductParams contains all the parameters to send to the API endpoint +for the get product operation typically these are written to a http.Request +*/ +type GetProductParams struct { + + /*ID + Id of the product to be retrieved + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get product params +func (o *GetProductParams) WithTimeout(timeout time.Duration) *GetProductParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get product params +func (o *GetProductParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get product params +func (o *GetProductParams) WithContext(ctx context.Context) *GetProductParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get product params +func (o *GetProductParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get product params +func (o *GetProductParams) WithHTTPClient(client *http.Client) *GetProductParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get product params +func (o *GetProductParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get product params +func (o *GetProductParams) WithID(id string) *GetProductParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get product params +func (o *GetProductParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetProductParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/product_management/get_product_responses.go b/services/customerdb/client/product_management/get_product_responses.go new file mode 100644 index 0000000..b4d6a5c --- /dev/null +++ b/services/customerdb/client/product_management/get_product_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetProductReader is a Reader for the GetProduct structure. +type GetProductReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetProductReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetProductOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetProductNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetProductInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetProductOK creates a GetProductOK with default headers values +func NewGetProductOK() *GetProductOK { + return &GetProductOK{} +} + +/*GetProductOK handles this case with default header values. + +Product with the id given in the system returned +*/ +type GetProductOK struct { + Payload *models.Product +} + +func (o *GetProductOK) Error() string { + return fmt.Sprintf("[GET /product/{id}][%d] getProductOK %+v", 200, o.Payload) +} + +func (o *GetProductOK) GetPayload() *models.Product { + return o.Payload +} + +func (o *GetProductOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Product) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetProductNotFound creates a GetProductNotFound with default headers values +func NewGetProductNotFound() *GetProductNotFound { + return &GetProductNotFound{} +} + +/*GetProductNotFound handles this case with default header values. + +The product with the given id wasn't found +*/ +type GetProductNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetProductNotFound) Error() string { + return fmt.Sprintf("[GET /product/{id}][%d] getProductNotFound %+v", 404, o.Payload) +} + +func (o *GetProductNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetProductNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetProductInternalServerError creates a GetProductInternalServerError with default headers values +func NewGetProductInternalServerError() *GetProductInternalServerError { + return &GetProductInternalServerError{} +} + +/*GetProductInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetProductInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetProductInternalServerError) Error() string { + return fmt.Sprintf("[GET /product/{id}][%d] getProductInternalServerError %+v", 500, o.Payload) +} + +func (o *GetProductInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetProductInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/product_management/list_products_parameters.go b/services/customerdb/client/product_management/list_products_parameters.go new file mode 100644 index 0000000..0f7223f --- /dev/null +++ b/services/customerdb/client/product_management/list_products_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListProductsParams creates a new ListProductsParams object +// with the default values initialized. +func NewListProductsParams() *ListProductsParams { + + return &ListProductsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListProductsParamsWithTimeout creates a new ListProductsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListProductsParamsWithTimeout(timeout time.Duration) *ListProductsParams { + + return &ListProductsParams{ + + timeout: timeout, + } +} + +// NewListProductsParamsWithContext creates a new ListProductsParams object +// with the default values initialized, and the ability to set a context for a request +func NewListProductsParamsWithContext(ctx context.Context) *ListProductsParams { + + return &ListProductsParams{ + + Context: ctx, + } +} + +// NewListProductsParamsWithHTTPClient creates a new ListProductsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListProductsParamsWithHTTPClient(client *http.Client) *ListProductsParams { + + return &ListProductsParams{ + HTTPClient: client, + } +} + +/*ListProductsParams contains all the parameters to send to the API endpoint +for the list products operation typically these are written to a http.Request +*/ +type ListProductsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list products params +func (o *ListProductsParams) WithTimeout(timeout time.Duration) *ListProductsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list products params +func (o *ListProductsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list products params +func (o *ListProductsParams) WithContext(ctx context.Context) *ListProductsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list products params +func (o *ListProductsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list products params +func (o *ListProductsParams) WithHTTPClient(client *http.Client) *ListProductsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list products params +func (o *ListProductsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListProductsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/product_management/list_products_responses.go b/services/customerdb/client/product_management/list_products_responses.go new file mode 100644 index 0000000..406db73 --- /dev/null +++ b/services/customerdb/client/product_management/list_products_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ListProductsReader is a Reader for the ListProducts structure. +type ListProductsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListProductsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListProductsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListProductsInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewListProductsOK creates a ListProductsOK with default headers values +func NewListProductsOK() *ListProductsOK { + return &ListProductsOK{} +} + +/*ListProductsOK handles this case with default header values. + +List of products in the system returned +*/ +type ListProductsOK struct { + Payload []*models.Product +} + +func (o *ListProductsOK) Error() string { + return fmt.Sprintf("[GET /product][%d] listProductsOK %+v", 200, o.Payload) +} + +func (o *ListProductsOK) GetPayload() []*models.Product { + return o.Payload +} + +func (o *ListProductsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListProductsInternalServerError creates a ListProductsInternalServerError with default headers values +func NewListProductsInternalServerError() *ListProductsInternalServerError { + return &ListProductsInternalServerError{} +} + +/*ListProductsInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListProductsInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListProductsInternalServerError) Error() string { + return fmt.Sprintf("[GET /product][%d] listProductsInternalServerError %+v", 500, o.Payload) +} + +func (o *ListProductsInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListProductsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/product_management/product_management_client.go b/services/customerdb/client/product_management/product_management_client.go new file mode 100644 index 0000000..6df63a2 --- /dev/null +++ b/services/customerdb/client/product_management/product_management_client.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the product management client +type API interface { + /* + AddProduct inserts a new product in the system*/ + AddProduct(ctx context.Context, params *AddProductParams) (*AddProductCreated, error) + /* + GetProduct returns the information about the product with the given id*/ + GetProduct(ctx context.Context, params *GetProductParams) (*GetProductOK, error) + /* + ListProducts lists all the products in the system*/ + ListProducts(ctx context.Context, params *ListProductsParams) (*ListProductsOK, error) + /* + UpdateProduct updates the information of the product with the given id*/ + UpdateProduct(ctx context.Context, params *UpdateProductParams) (*UpdateProductOK, error) +} + +// New creates a new product management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for product management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +AddProduct inserts a new product in the system +*/ +func (a *Client) AddProduct(ctx context.Context, params *AddProductParams) (*AddProductCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "addProduct", + Method: "POST", + PathPattern: "/product", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &AddProductReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*AddProductCreated), nil + +} + +/* +GetProduct returns the information about the product with the given id +*/ +func (a *Client) GetProduct(ctx context.Context, params *GetProductParams) (*GetProductOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getProduct", + Method: "GET", + PathPattern: "/product/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetProductReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetProductOK), nil + +} + +/* +ListProducts lists all the products in the system +*/ +func (a *Client) ListProducts(ctx context.Context, params *ListProductsParams) (*ListProductsOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listProducts", + Method: "GET", + PathPattern: "/product", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListProductsReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListProductsOK), nil + +} + +/* +UpdateProduct updates the information of the product with the given id +*/ +func (a *Client) UpdateProduct(ctx context.Context, params *UpdateProductParams) (*UpdateProductOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updateProduct", + Method: "PUT", + PathPattern: "/product/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdateProductReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UpdateProductOK), nil + +} diff --git a/services/customerdb/client/product_management/update_product_parameters.go b/services/customerdb/client/product_management/update_product_parameters.go new file mode 100644 index 0000000..eeceeda --- /dev/null +++ b/services/customerdb/client/product_management/update_product_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewUpdateProductParams creates a new UpdateProductParams object +// with the default values initialized. +func NewUpdateProductParams() *UpdateProductParams { + var () + return &UpdateProductParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateProductParamsWithTimeout creates a new UpdateProductParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdateProductParamsWithTimeout(timeout time.Duration) *UpdateProductParams { + var () + return &UpdateProductParams{ + + timeout: timeout, + } +} + +// NewUpdateProductParamsWithContext creates a new UpdateProductParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdateProductParamsWithContext(ctx context.Context) *UpdateProductParams { + var () + return &UpdateProductParams{ + + Context: ctx, + } +} + +// NewUpdateProductParamsWithHTTPClient creates a new UpdateProductParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdateProductParamsWithHTTPClient(client *http.Client) *UpdateProductParams { + var () + return &UpdateProductParams{ + HTTPClient: client, + } +} + +/*UpdateProductParams contains all the parameters to send to the API endpoint +for the update product operation typically these are written to a http.Request +*/ +type UpdateProductParams struct { + + /*ID + Id of the product to be updated + + */ + ID string + /*Product + Product to be updated + + */ + Product *models.Product + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update product params +func (o *UpdateProductParams) WithTimeout(timeout time.Duration) *UpdateProductParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update product params +func (o *UpdateProductParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update product params +func (o *UpdateProductParams) WithContext(ctx context.Context) *UpdateProductParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update product params +func (o *UpdateProductParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update product params +func (o *UpdateProductParams) WithHTTPClient(client *http.Client) *UpdateProductParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update product params +func (o *UpdateProductParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the update product params +func (o *UpdateProductParams) WithID(id string) *UpdateProductParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update product params +func (o *UpdateProductParams) SetID(id string) { + o.ID = id +} + +// WithProduct adds the product to the update product params +func (o *UpdateProductParams) WithProduct(product *models.Product) *UpdateProductParams { + o.SetProduct(product) + return o +} + +// SetProduct adds the product to the update product params +func (o *UpdateProductParams) SetProduct(product *models.Product) { + o.Product = product +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateProductParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Product != nil { + if err := r.SetBodyParam(o.Product); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/product_management/update_product_responses.go b/services/customerdb/client/product_management/update_product_responses.go new file mode 100644 index 0000000..e42ebf5 --- /dev/null +++ b/services/customerdb/client/product_management/update_product_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// UpdateProductReader is a Reader for the UpdateProduct structure. +type UpdateProductReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateProductReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateProductOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdateProductNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdateProductInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewUpdateProductOK creates a UpdateProductOK with default headers values +func NewUpdateProductOK() *UpdateProductOK { + return &UpdateProductOK{} +} + +/*UpdateProductOK handles this case with default header values. + +Product with the given id was updated +*/ +type UpdateProductOK struct { + Payload *models.ItemCreatedResponse +} + +func (o *UpdateProductOK) Error() string { + return fmt.Sprintf("[PUT /product/{id}][%d] updateProductOK %+v", 200, o.Payload) +} + +func (o *UpdateProductOK) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *UpdateProductOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateProductNotFound creates a UpdateProductNotFound with default headers values +func NewUpdateProductNotFound() *UpdateProductNotFound { + return &UpdateProductNotFound{} +} + +/*UpdateProductNotFound handles this case with default header values. + +The product with the given id wasn't found +*/ +type UpdateProductNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdateProductNotFound) Error() string { + return fmt.Sprintf("[PUT /product/{id}][%d] updateProductNotFound %+v", 404, o.Payload) +} + +func (o *UpdateProductNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateProductNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateProductInternalServerError creates a UpdateProductInternalServerError with default headers values +func NewUpdateProductInternalServerError() *UpdateProductInternalServerError { + return &UpdateProductInternalServerError{} +} + +/*UpdateProductInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type UpdateProductInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdateProductInternalServerError) Error() string { + return fmt.Sprintf("[PUT /product/{id}][%d] updateProductInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdateProductInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateProductInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/reseller_management/add_reseller_parameters.go b/services/customerdb/client/reseller_management/add_reseller_parameters.go new file mode 100644 index 0000000..dbd0e2d --- /dev/null +++ b/services/customerdb/client/reseller_management/add_reseller_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewAddResellerParams creates a new AddResellerParams object +// with the default values initialized. +func NewAddResellerParams() *AddResellerParams { + var () + return &AddResellerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewAddResellerParamsWithTimeout creates a new AddResellerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewAddResellerParamsWithTimeout(timeout time.Duration) *AddResellerParams { + var () + return &AddResellerParams{ + + timeout: timeout, + } +} + +// NewAddResellerParamsWithContext creates a new AddResellerParams object +// with the default values initialized, and the ability to set a context for a request +func NewAddResellerParamsWithContext(ctx context.Context) *AddResellerParams { + var () + return &AddResellerParams{ + + Context: ctx, + } +} + +// NewAddResellerParamsWithHTTPClient creates a new AddResellerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewAddResellerParamsWithHTTPClient(client *http.Client) *AddResellerParams { + var () + return &AddResellerParams{ + HTTPClient: client, + } +} + +/*AddResellerParams contains all the parameters to send to the API endpoint +for the add reseller operation typically these are written to a http.Request +*/ +type AddResellerParams struct { + + /*Reseller + Reseller to be added + + */ + Reseller *models.Reseller + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the add reseller params +func (o *AddResellerParams) WithTimeout(timeout time.Duration) *AddResellerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add reseller params +func (o *AddResellerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add reseller params +func (o *AddResellerParams) WithContext(ctx context.Context) *AddResellerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add reseller params +func (o *AddResellerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add reseller params +func (o *AddResellerParams) WithHTTPClient(client *http.Client) *AddResellerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add reseller params +func (o *AddResellerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithReseller adds the reseller to the add reseller params +func (o *AddResellerParams) WithReseller(reseller *models.Reseller) *AddResellerParams { + o.SetReseller(reseller) + return o +} + +// SetReseller adds the reseller to the add reseller params +func (o *AddResellerParams) SetReseller(reseller *models.Reseller) { + o.Reseller = reseller +} + +// WriteToRequest writes these params to a swagger request +func (o *AddResellerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Reseller != nil { + if err := r.SetBodyParam(o.Reseller); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/reseller_management/add_reseller_responses.go b/services/customerdb/client/reseller_management/add_reseller_responses.go new file mode 100644 index 0000000..dc942f6 --- /dev/null +++ b/services/customerdb/client/reseller_management/add_reseller_responses.go @@ -0,0 +1,213 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// AddResellerReader is a Reader for the AddReseller structure. +type AddResellerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddResellerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewAddResellerCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 202: + result := NewAddResellerAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewAddResellerBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewAddResellerConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewAddResellerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewAddResellerCreated creates a AddResellerCreated with default headers values +func NewAddResellerCreated() *AddResellerCreated { + return &AddResellerCreated{} +} + +/*AddResellerCreated handles this case with default header values. + +New reseller was added successfully +*/ +type AddResellerCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *AddResellerCreated) Error() string { + return fmt.Sprintf("[POST /reseller][%d] addResellerCreated %+v", 201, o.Payload) +} + +func (o *AddResellerCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *AddResellerCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddResellerAccepted creates a AddResellerAccepted with default headers values +func NewAddResellerAccepted() *AddResellerAccepted { + return &AddResellerAccepted{} +} + +/*AddResellerAccepted handles this case with default header values. + +The new reseller was added but there might have been some fails when adding part of the data +*/ +type AddResellerAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *AddResellerAccepted) Error() string { + return fmt.Sprintf("[POST /reseller][%d] addResellerAccepted %+v", 202, o.Payload) +} + +func (o *AddResellerAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *AddResellerAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddResellerBadRequest creates a AddResellerBadRequest with default headers values +func NewAddResellerBadRequest() *AddResellerBadRequest { + return &AddResellerBadRequest{} +} + +/*AddResellerBadRequest handles this case with default header values. + +Invalid input, object invalid +*/ +type AddResellerBadRequest struct { +} + +func (o *AddResellerBadRequest) Error() string { + return fmt.Sprintf("[POST /reseller][%d] addResellerBadRequest ", 400) +} + +func (o *AddResellerBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewAddResellerConflict creates a AddResellerConflict with default headers values +func NewAddResellerConflict() *AddResellerConflict { + return &AddResellerConflict{} +} + +/*AddResellerConflict handles this case with default header values. + +The given item already exists +*/ +type AddResellerConflict struct { + Payload *models.ErrorResponse +} + +func (o *AddResellerConflict) Error() string { + return fmt.Sprintf("[POST /reseller][%d] addResellerConflict %+v", 409, o.Payload) +} + +func (o *AddResellerConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddResellerConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddResellerInternalServerError creates a AddResellerInternalServerError with default headers values +func NewAddResellerInternalServerError() *AddResellerInternalServerError { + return &AddResellerInternalServerError{} +} + +/*AddResellerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type AddResellerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *AddResellerInternalServerError) Error() string { + return fmt.Sprintf("[POST /reseller][%d] addResellerInternalServerError %+v", 500, o.Payload) +} + +func (o *AddResellerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddResellerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/reseller_management/get_reseller_parameters.go b/services/customerdb/client/reseller_management/get_reseller_parameters.go new file mode 100644 index 0000000..75d25e0 --- /dev/null +++ b/services/customerdb/client/reseller_management/get_reseller_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetResellerParams creates a new GetResellerParams object +// with the default values initialized. +func NewGetResellerParams() *GetResellerParams { + var () + return &GetResellerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetResellerParamsWithTimeout creates a new GetResellerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetResellerParamsWithTimeout(timeout time.Duration) *GetResellerParams { + var () + return &GetResellerParams{ + + timeout: timeout, + } +} + +// NewGetResellerParamsWithContext creates a new GetResellerParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetResellerParamsWithContext(ctx context.Context) *GetResellerParams { + var () + return &GetResellerParams{ + + Context: ctx, + } +} + +// NewGetResellerParamsWithHTTPClient creates a new GetResellerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetResellerParamsWithHTTPClient(client *http.Client) *GetResellerParams { + var () + return &GetResellerParams{ + HTTPClient: client, + } +} + +/*GetResellerParams contains all the parameters to send to the API endpoint +for the get reseller operation typically these are written to a http.Request +*/ +type GetResellerParams struct { + + /*ID + Id of the reseller to be retrieved + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get reseller params +func (o *GetResellerParams) WithTimeout(timeout time.Duration) *GetResellerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get reseller params +func (o *GetResellerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get reseller params +func (o *GetResellerParams) WithContext(ctx context.Context) *GetResellerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get reseller params +func (o *GetResellerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get reseller params +func (o *GetResellerParams) WithHTTPClient(client *http.Client) *GetResellerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get reseller params +func (o *GetResellerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get reseller params +func (o *GetResellerParams) WithID(id string) *GetResellerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get reseller params +func (o *GetResellerParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetResellerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/reseller_management/get_reseller_responses.go b/services/customerdb/client/reseller_management/get_reseller_responses.go new file mode 100644 index 0000000..c2032ac --- /dev/null +++ b/services/customerdb/client/reseller_management/get_reseller_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetResellerReader is a Reader for the GetReseller structure. +type GetResellerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetResellerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetResellerOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetResellerNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetResellerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetResellerOK creates a GetResellerOK with default headers values +func NewGetResellerOK() *GetResellerOK { + return &GetResellerOK{} +} + +/*GetResellerOK handles this case with default header values. + +Reseller with the id given in the system returned +*/ +type GetResellerOK struct { + Payload *models.Reseller +} + +func (o *GetResellerOK) Error() string { + return fmt.Sprintf("[GET /reseller/{id}][%d] getResellerOK %+v", 200, o.Payload) +} + +func (o *GetResellerOK) GetPayload() *models.Reseller { + return o.Payload +} + +func (o *GetResellerOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Reseller) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetResellerNotFound creates a GetResellerNotFound with default headers values +func NewGetResellerNotFound() *GetResellerNotFound { + return &GetResellerNotFound{} +} + +/*GetResellerNotFound handles this case with default header values. + +The reseller with the given id wasn't found +*/ +type GetResellerNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetResellerNotFound) Error() string { + return fmt.Sprintf("[GET /reseller/{id}][%d] getResellerNotFound %+v", 404, o.Payload) +} + +func (o *GetResellerNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetResellerNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetResellerInternalServerError creates a GetResellerInternalServerError with default headers values +func NewGetResellerInternalServerError() *GetResellerInternalServerError { + return &GetResellerInternalServerError{} +} + +/*GetResellerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetResellerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetResellerInternalServerError) Error() string { + return fmt.Sprintf("[GET /reseller/{id}][%d] getResellerInternalServerError %+v", 500, o.Payload) +} + +func (o *GetResellerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetResellerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/reseller_management/list_resellers_parameters.go b/services/customerdb/client/reseller_management/list_resellers_parameters.go new file mode 100644 index 0000000..cd99d3b --- /dev/null +++ b/services/customerdb/client/reseller_management/list_resellers_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListResellersParams creates a new ListResellersParams object +// with the default values initialized. +func NewListResellersParams() *ListResellersParams { + + return &ListResellersParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListResellersParamsWithTimeout creates a new ListResellersParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListResellersParamsWithTimeout(timeout time.Duration) *ListResellersParams { + + return &ListResellersParams{ + + timeout: timeout, + } +} + +// NewListResellersParamsWithContext creates a new ListResellersParams object +// with the default values initialized, and the ability to set a context for a request +func NewListResellersParamsWithContext(ctx context.Context) *ListResellersParams { + + return &ListResellersParams{ + + Context: ctx, + } +} + +// NewListResellersParamsWithHTTPClient creates a new ListResellersParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListResellersParamsWithHTTPClient(client *http.Client) *ListResellersParams { + + return &ListResellersParams{ + HTTPClient: client, + } +} + +/*ListResellersParams contains all the parameters to send to the API endpoint +for the list resellers operation typically these are written to a http.Request +*/ +type ListResellersParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list resellers params +func (o *ListResellersParams) WithTimeout(timeout time.Duration) *ListResellersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list resellers params +func (o *ListResellersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list resellers params +func (o *ListResellersParams) WithContext(ctx context.Context) *ListResellersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list resellers params +func (o *ListResellersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list resellers params +func (o *ListResellersParams) WithHTTPClient(client *http.Client) *ListResellersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list resellers params +func (o *ListResellersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListResellersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/reseller_management/list_resellers_responses.go b/services/customerdb/client/reseller_management/list_resellers_responses.go new file mode 100644 index 0000000..2cee0f6 --- /dev/null +++ b/services/customerdb/client/reseller_management/list_resellers_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ListResellersReader is a Reader for the ListResellers structure. +type ListResellersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListResellersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListResellersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListResellersInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewListResellersOK creates a ListResellersOK with default headers values +func NewListResellersOK() *ListResellersOK { + return &ListResellersOK{} +} + +/*ListResellersOK handles this case with default header values. + +List of resellers in the system returned +*/ +type ListResellersOK struct { + Payload []*models.Reseller +} + +func (o *ListResellersOK) Error() string { + return fmt.Sprintf("[GET /reseller][%d] listResellersOK %+v", 200, o.Payload) +} + +func (o *ListResellersOK) GetPayload() []*models.Reseller { + return o.Payload +} + +func (o *ListResellersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListResellersInternalServerError creates a ListResellersInternalServerError with default headers values +func NewListResellersInternalServerError() *ListResellersInternalServerError { + return &ListResellersInternalServerError{} +} + +/*ListResellersInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListResellersInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListResellersInternalServerError) Error() string { + return fmt.Sprintf("[GET /reseller][%d] listResellersInternalServerError %+v", 500, o.Payload) +} + +func (o *ListResellersInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListResellersInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/reseller_management/reseller_management_client.go b/services/customerdb/client/reseller_management/reseller_management_client.go new file mode 100644 index 0000000..60391b2 --- /dev/null +++ b/services/customerdb/client/reseller_management/reseller_management_client.go @@ -0,0 +1,162 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the reseller management client +type API interface { + /* + AddReseller inserts a new reseller in the system*/ + AddReseller(ctx context.Context, params *AddResellerParams) (*AddResellerCreated, *AddResellerAccepted, error) + /* + GetReseller returns the information about the reseller with the given id*/ + GetReseller(ctx context.Context, params *GetResellerParams) (*GetResellerOK, error) + /* + ListResellers lists all the resellers in the system*/ + ListResellers(ctx context.Context, params *ListResellersParams) (*ListResellersOK, error) + /* + UpdateReseller updates the information of the reseller with the given id*/ + UpdateReseller(ctx context.Context, params *UpdateResellerParams) (*UpdateResellerOK, *UpdateResellerAccepted, error) +} + +// New creates a new reseller management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for reseller management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +AddReseller inserts a new reseller in the system +*/ +func (a *Client) AddReseller(ctx context.Context, params *AddResellerParams) (*AddResellerCreated, *AddResellerAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "addReseller", + Method: "POST", + PathPattern: "/reseller", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &AddResellerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, nil, err + } + switch value := result.(type) { + case *AddResellerCreated: + return value, nil, nil + case *AddResellerAccepted: + return nil, value, nil + } + return nil, nil, nil + +} + +/* +GetReseller returns the information about the reseller with the given id +*/ +func (a *Client) GetReseller(ctx context.Context, params *GetResellerParams) (*GetResellerOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getReseller", + Method: "GET", + PathPattern: "/reseller/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetResellerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetResellerOK), nil + +} + +/* +ListResellers lists all the resellers in the system +*/ +func (a *Client) ListResellers(ctx context.Context, params *ListResellersParams) (*ListResellersOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listResellers", + Method: "GET", + PathPattern: "/reseller", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListResellersReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListResellersOK), nil + +} + +/* +UpdateReseller updates the information of the reseller with the given id +*/ +func (a *Client) UpdateReseller(ctx context.Context, params *UpdateResellerParams) (*UpdateResellerOK, *UpdateResellerAccepted, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updateReseller", + Method: "PUT", + PathPattern: "/reseller/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdateResellerReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, nil, err + } + switch value := result.(type) { + case *UpdateResellerOK: + return value, nil, nil + case *UpdateResellerAccepted: + return nil, value, nil + } + return nil, nil, nil + +} diff --git a/services/customerdb/client/reseller_management/update_reseller_parameters.go b/services/customerdb/client/reseller_management/update_reseller_parameters.go new file mode 100644 index 0000000..65fd8d5 --- /dev/null +++ b/services/customerdb/client/reseller_management/update_reseller_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewUpdateResellerParams creates a new UpdateResellerParams object +// with the default values initialized. +func NewUpdateResellerParams() *UpdateResellerParams { + var () + return &UpdateResellerParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateResellerParamsWithTimeout creates a new UpdateResellerParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdateResellerParamsWithTimeout(timeout time.Duration) *UpdateResellerParams { + var () + return &UpdateResellerParams{ + + timeout: timeout, + } +} + +// NewUpdateResellerParamsWithContext creates a new UpdateResellerParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdateResellerParamsWithContext(ctx context.Context) *UpdateResellerParams { + var () + return &UpdateResellerParams{ + + Context: ctx, + } +} + +// NewUpdateResellerParamsWithHTTPClient creates a new UpdateResellerParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdateResellerParamsWithHTTPClient(client *http.Client) *UpdateResellerParams { + var () + return &UpdateResellerParams{ + HTTPClient: client, + } +} + +/*UpdateResellerParams contains all the parameters to send to the API endpoint +for the update reseller operation typically these are written to a http.Request +*/ +type UpdateResellerParams struct { + + /*ID + Id of the reseller to be updated + + */ + ID string + /*Reseller + Reseller to be updated + + */ + Reseller *models.Reseller + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update reseller params +func (o *UpdateResellerParams) WithTimeout(timeout time.Duration) *UpdateResellerParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update reseller params +func (o *UpdateResellerParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update reseller params +func (o *UpdateResellerParams) WithContext(ctx context.Context) *UpdateResellerParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update reseller params +func (o *UpdateResellerParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update reseller params +func (o *UpdateResellerParams) WithHTTPClient(client *http.Client) *UpdateResellerParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update reseller params +func (o *UpdateResellerParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the update reseller params +func (o *UpdateResellerParams) WithID(id string) *UpdateResellerParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update reseller params +func (o *UpdateResellerParams) SetID(id string) { + o.ID = id +} + +// WithReseller adds the reseller to the update reseller params +func (o *UpdateResellerParams) WithReseller(reseller *models.Reseller) *UpdateResellerParams { + o.SetReseller(reseller) + return o +} + +// SetReseller adds the reseller to the update reseller params +func (o *UpdateResellerParams) SetReseller(reseller *models.Reseller) { + o.Reseller = reseller +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateResellerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Reseller != nil { + if err := r.SetBodyParam(o.Reseller); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/reseller_management/update_reseller_responses.go b/services/customerdb/client/reseller_management/update_reseller_responses.go new file mode 100644 index 0000000..12f638a --- /dev/null +++ b/services/customerdb/client/reseller_management/update_reseller_responses.go @@ -0,0 +1,186 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// UpdateResellerReader is a Reader for the UpdateReseller structure. +type UpdateResellerReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateResellerReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateResellerOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 202: + result := NewUpdateResellerAccepted() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdateResellerNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdateResellerInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewUpdateResellerOK creates a UpdateResellerOK with default headers values +func NewUpdateResellerOK() *UpdateResellerOK { + return &UpdateResellerOK{} +} + +/*UpdateResellerOK handles this case with default header values. + +Reseller with the given id was updated +*/ +type UpdateResellerOK struct { + Payload *models.ItemCreatedResponse +} + +func (o *UpdateResellerOK) Error() string { + return fmt.Sprintf("[PUT /reseller/{id}][%d] updateResellerOK %+v", 200, o.Payload) +} + +func (o *UpdateResellerOK) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *UpdateResellerOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateResellerAccepted creates a UpdateResellerAccepted with default headers values +func NewUpdateResellerAccepted() *UpdateResellerAccepted { + return &UpdateResellerAccepted{} +} + +/*UpdateResellerAccepted handles this case with default header values. + +The reseller was updated but there might have been some fails when adding part of the data +*/ +type UpdateResellerAccepted struct { + Payload *models.ItemCreatedResponse +} + +func (o *UpdateResellerAccepted) Error() string { + return fmt.Sprintf("[PUT /reseller/{id}][%d] updateResellerAccepted %+v", 202, o.Payload) +} + +func (o *UpdateResellerAccepted) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *UpdateResellerAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateResellerNotFound creates a UpdateResellerNotFound with default headers values +func NewUpdateResellerNotFound() *UpdateResellerNotFound { + return &UpdateResellerNotFound{} +} + +/*UpdateResellerNotFound handles this case with default header values. + +The reseller with the given id wasn't found +*/ +type UpdateResellerNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdateResellerNotFound) Error() string { + return fmt.Sprintf("[PUT /reseller/{id}][%d] updateResellerNotFound %+v", 404, o.Payload) +} + +func (o *UpdateResellerNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateResellerNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateResellerInternalServerError creates a UpdateResellerInternalServerError with default headers values +func NewUpdateResellerInternalServerError() *UpdateResellerInternalServerError { + return &UpdateResellerInternalServerError{} +} + +/*UpdateResellerInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type UpdateResellerInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdateResellerInternalServerError) Error() string { + return fmt.Sprintf("[PUT /reseller/{id}][%d] updateResellerInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdateResellerInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateResellerInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/status_management/get_status_parameters.go b/services/customerdb/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..35b2173 --- /dev/null +++ b/services/customerdb/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the product to be retrieved + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/status_management/get_status_responses.go b/services/customerdb/client/status_management/get_status_responses.go new file mode 100644 index 0000000..07bd065 --- /dev/null +++ b/services/customerdb/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/status_management/show_status_parameters.go b/services/customerdb/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/services/customerdb/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/status_management/show_status_responses.go b/services/customerdb/client/status_management/show_status_responses.go new file mode 100644 index 0000000..e4321f6 --- /dev/null +++ b/services/customerdb/client/status_management/show_status_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/status_management/status_management_client.go b/services/customerdb/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/services/customerdb/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/services/customerdb/client/trigger_management/exec_sample_parameters.go b/services/customerdb/client/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..2e1428d --- /dev/null +++ b/services/customerdb/client/trigger_management/exec_sample_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// with the default values initialized. +func NewExecSampleParams() *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewExecSampleParamsWithTimeout creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewExecSampleParamsWithTimeout(timeout time.Duration) *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: timeout, + } +} + +// NewExecSampleParamsWithContext creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a context for a request +func NewExecSampleParamsWithContext(ctx context.Context) *ExecSampleParams { + + return &ExecSampleParams{ + + Context: ctx, + } +} + +// NewExecSampleParamsWithHTTPClient creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewExecSampleParamsWithHTTPClient(client *http.Client) *ExecSampleParams { + + return &ExecSampleParams{ + HTTPClient: client, + } +} + +/*ExecSampleParams contains all the parameters to send to the API endpoint +for the exec sample operation typically these are written to a http.Request +*/ +type ExecSampleParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) WithTimeout(timeout time.Duration) *ExecSampleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the exec sample params +func (o *ExecSampleParams) WithContext(ctx context.Context) *ExecSampleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the exec sample params +func (o *ExecSampleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) WithHTTPClient(client *http.Client) *ExecSampleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ExecSampleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/client/trigger_management/exec_sample_responses.go b/services/customerdb/client/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..46fbfda --- /dev/null +++ b/services/customerdb/client/trigger_management/exec_sample_responses.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ExecSampleReader is a Reader for the ExecSample structure. +type ExecSampleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ExecSampleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewExecSampleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewExecSampleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("unknown error", response, response.Code()) + } +} + +// NewExecSampleOK creates a ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + return &ExecSampleOK{} +} + +/*ExecSampleOK handles this case with default header values. + +Sample task executed successfully +*/ +type ExecSampleOK struct { +} + +func (o *ExecSampleOK) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleOK ", 200) +} + +func (o *ExecSampleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewExecSampleInternalServerError creates a ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + return &ExecSampleInternalServerError{} +} + +/*ExecSampleInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ExecSampleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ExecSampleInternalServerError) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleInternalServerError %+v", 500, o.Payload) +} + +func (o *ExecSampleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ExecSampleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/customerdb/client/trigger_management/trigger_management_client.go b/services/customerdb/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..b8010e0 --- /dev/null +++ b/services/customerdb/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + ExecSample samples task trigger*/ + ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +ExecSample samples task trigger +*/ +func (a *Client) ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "execSample", + Method: "GET", + PathPattern: "/trigger/sample", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ExecSampleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ExecSampleOK), nil + +} diff --git a/services/customerdb/go.mod b/services/customerdb/go.mod new file mode 100644 index 0000000..bf786f7 --- /dev/null +++ b/services/customerdb/go.mod @@ -0,0 +1,34 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb + +go 1.15 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/go-openapi/analysis v0.21.1 // indirect + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/go-resty/resty/v2 v2.7.0 // indirect + github.com/go-stack/stack v1.8.1 // indirect + github.com/jackc/pgx/v4 v4.14.1 // indirect + github.com/jinzhu/now v1.1.4 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/rs/cors v1.8.2 + github.com/segmentio/ksuid v1.0.4 // indirect + github.com/spf13/viper v1.10.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + go.mongodb.org/mongo-driver v1.8.1 // indirect + golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect + golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect + golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/services/customerdb/models/customer.go b/services/customerdb/models/customer.go new file mode 100644 index 0000000..dae4e42 --- /dev/null +++ b/services/customerdb/models/customer.go @@ -0,0 +1,1567 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Customer customer +// +// swagger:model Customer +type Customer struct { + + // abacus code + AbacusCode string `json:"AbacusCode,omitempty" gorm:"default:''"` + + // address + Address string `json:"Address,omitempty"` + + // Api link + APILink string `json:"ApiLink,omitempty" gorm:"-"` + + // bill contact + BillContact string `json:"BillContact,omitempty" gorm:"default:''"` + + // ISO-4217 currency code + // Enum: [AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BOV BRL BSD BTN BWP BYN BZD CAD CDF CHE CHF CHW CLF CLP CNY COP COU CRC CUC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HRK HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLL SOS SRD SSP STN SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD USN UYI UYU UYW UZS VES VND VUV WST XAF XAG XAU XBA XBB XBC XBD XCD XDR XOF XPD XPF XPT XSU XTS XUA XXX YER ZAR ZMW ZWL] + BillCurrency *string `json:"BillCurrency,omitempty" gorm:"default:CHF"` + + // bill period + // Enum: [daily weekly bi-weekly monthly bi-monthly quarterly semi-annually annually] + BillPeriod *string `json:"BillPeriod,omitempty" gorm:"default:monthly"` + + // billable + Billable *bool `json:"Billable,omitempty" gorm:"default:true"` + + // billing code + BillingCode string `json:"BillingCode,omitempty" gorm:"default:''"` + + // cancel date + // Format: date + CancelDate strfmt.Date `json:"CancelDate,omitempty" gorm:"type:date;default:2100-12-31"` + + // contract end + // Format: date + ContractEnd strfmt.Date `json:"ContractEnd,omitempty" gorm:"type:date;default:2030-12-31"` + + // contract start + // Format: date + ContractStart strfmt.Date `json:"ContractStart,omitempty" gorm:"type:date;default:2019-01-01"` + + // customer Id + CustomerID string `json:"CustomerId,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // deleted at + // Format: datetime + DeletedAt *strfmt.DateTime `json:"DeletedAt,omitempty" gorm:"type:timestamptz"` + + // discount + Discount float64 `json:"Discount,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // email bcc + // Format: email + EmailBcc strfmt.Email `json:"EmailBcc,omitempty" gorm:"default:''"` + + // email cc + // Format: email + EmailCc strfmt.Email `json:"EmailCc,omitempty" gorm:"default:''"` + + // email to + // Format: email + EmailTo strfmt.Email `json:"EmailTo,omitempty" gorm:"default:''"` + + // invoice mode + // Enum: [email post] + InvoiceMode *string `json:"InvoiceMode,omitempty" gorm:"default:email"` + + // is active + IsActive *bool `json:"IsActive,omitempty" gorm:"default:true"` + + // ISO-369-1 alpha-2 language codes + // Enum: [AA AB AE AF AK AM AN AR AS AV AY AZ BA BE BG BH BI BM BN BO BR BS CA CE CH CO CR CS CU CV CY DA DE DV DZ EE EL EN EO ES ET EU FA FF FI FJ FO FR FY GA GD GL GN GU GV HA HE HI HO HR HT HU HY HZ IA ID IE IG II IK IO IS IT IU JA JV KA KG KI KJ KK KL KM KN KO KR KS KU KV KW KY LA LB LG LI LN LO LT LU LV MG MH MI MK ML MN MR MS MT MY NA NB ND NE NG NL NN NO NR NV NY OC OJ OM OR OS PA PI PL PS PT QU RM RN RO RU RW SA SC SD SE SG SI SK SL SM SN SO SQ SR SS ST SU SV SW TA TE TG TH TI TK TL TN TO TR TS TT TW TY UG UK UR UZ VE VI VO WA WO XH YI YO ZA ZH ZU] + Language *string `json:"Language,omitempty" gorm:"default:DE"` + + // name + Name string `json:"Name,omitempty"` + + // parent customer Id + ParentCustomerID string `json:"ParentCustomerId,omitempty"` + + // plan Id + PlanID string `json:"PlanId,omitempty" gorm:"default:'DEFAULT'"` + + // products + Products []*Product `json:"Products" gorm:"-"` + + // reseller Id + ResellerID string `json:"ResellerId,omitempty"` +} + +// Validate validates this customer +func (m *Customer) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBillCurrency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBillPeriod(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCancelDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContractEnd(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContractStart(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeletedAt(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmailBcc(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmailCc(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmailTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInvoiceMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLanguage(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProducts(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var customerTypeBillCurrencyPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HRK","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLL","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VES","VND","VUV","WST","XAF","XAG","XAU","XBA","XBB","XBC","XBD","XCD","XDR","XOF","XPD","XPF","XPT","XSU","XTS","XUA","XXX","YER","ZAR","ZMW","ZWL"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + customerTypeBillCurrencyPropEnum = append(customerTypeBillCurrencyPropEnum, v) + } +} + +const ( + + // CustomerBillCurrencyAED captures enum value "AED" + CustomerBillCurrencyAED string = "AED" + + // CustomerBillCurrencyAFN captures enum value "AFN" + CustomerBillCurrencyAFN string = "AFN" + + // CustomerBillCurrencyALL captures enum value "ALL" + CustomerBillCurrencyALL string = "ALL" + + // CustomerBillCurrencyAMD captures enum value "AMD" + CustomerBillCurrencyAMD string = "AMD" + + // CustomerBillCurrencyANG captures enum value "ANG" + CustomerBillCurrencyANG string = "ANG" + + // CustomerBillCurrencyAOA captures enum value "AOA" + CustomerBillCurrencyAOA string = "AOA" + + // CustomerBillCurrencyARS captures enum value "ARS" + CustomerBillCurrencyARS string = "ARS" + + // CustomerBillCurrencyAUD captures enum value "AUD" + CustomerBillCurrencyAUD string = "AUD" + + // CustomerBillCurrencyAWG captures enum value "AWG" + CustomerBillCurrencyAWG string = "AWG" + + // CustomerBillCurrencyAZN captures enum value "AZN" + CustomerBillCurrencyAZN string = "AZN" + + // CustomerBillCurrencyBAM captures enum value "BAM" + CustomerBillCurrencyBAM string = "BAM" + + // CustomerBillCurrencyBBD captures enum value "BBD" + CustomerBillCurrencyBBD string = "BBD" + + // CustomerBillCurrencyBDT captures enum value "BDT" + CustomerBillCurrencyBDT string = "BDT" + + // CustomerBillCurrencyBGN captures enum value "BGN" + CustomerBillCurrencyBGN string = "BGN" + + // CustomerBillCurrencyBHD captures enum value "BHD" + CustomerBillCurrencyBHD string = "BHD" + + // CustomerBillCurrencyBIF captures enum value "BIF" + CustomerBillCurrencyBIF string = "BIF" + + // CustomerBillCurrencyBMD captures enum value "BMD" + CustomerBillCurrencyBMD string = "BMD" + + // CustomerBillCurrencyBND captures enum value "BND" + CustomerBillCurrencyBND string = "BND" + + // CustomerBillCurrencyBOB captures enum value "BOB" + CustomerBillCurrencyBOB string = "BOB" + + // CustomerBillCurrencyBOV captures enum value "BOV" + CustomerBillCurrencyBOV string = "BOV" + + // CustomerBillCurrencyBRL captures enum value "BRL" + CustomerBillCurrencyBRL string = "BRL" + + // CustomerBillCurrencyBSD captures enum value "BSD" + CustomerBillCurrencyBSD string = "BSD" + + // CustomerBillCurrencyBTN captures enum value "BTN" + CustomerBillCurrencyBTN string = "BTN" + + // CustomerBillCurrencyBWP captures enum value "BWP" + CustomerBillCurrencyBWP string = "BWP" + + // CustomerBillCurrencyBYN captures enum value "BYN" + CustomerBillCurrencyBYN string = "BYN" + + // CustomerBillCurrencyBZD captures enum value "BZD" + CustomerBillCurrencyBZD string = "BZD" + + // CustomerBillCurrencyCAD captures enum value "CAD" + CustomerBillCurrencyCAD string = "CAD" + + // CustomerBillCurrencyCDF captures enum value "CDF" + CustomerBillCurrencyCDF string = "CDF" + + // CustomerBillCurrencyCHE captures enum value "CHE" + CustomerBillCurrencyCHE string = "CHE" + + // CustomerBillCurrencyCHF captures enum value "CHF" + CustomerBillCurrencyCHF string = "CHF" + + // CustomerBillCurrencyCHW captures enum value "CHW" + CustomerBillCurrencyCHW string = "CHW" + + // CustomerBillCurrencyCLF captures enum value "CLF" + CustomerBillCurrencyCLF string = "CLF" + + // CustomerBillCurrencyCLP captures enum value "CLP" + CustomerBillCurrencyCLP string = "CLP" + + // CustomerBillCurrencyCNY captures enum value "CNY" + CustomerBillCurrencyCNY string = "CNY" + + // CustomerBillCurrencyCOP captures enum value "COP" + CustomerBillCurrencyCOP string = "COP" + + // CustomerBillCurrencyCOU captures enum value "COU" + CustomerBillCurrencyCOU string = "COU" + + // CustomerBillCurrencyCRC captures enum value "CRC" + CustomerBillCurrencyCRC string = "CRC" + + // CustomerBillCurrencyCUC captures enum value "CUC" + CustomerBillCurrencyCUC string = "CUC" + + // CustomerBillCurrencyCUP captures enum value "CUP" + CustomerBillCurrencyCUP string = "CUP" + + // CustomerBillCurrencyCVE captures enum value "CVE" + CustomerBillCurrencyCVE string = "CVE" + + // CustomerBillCurrencyCZK captures enum value "CZK" + CustomerBillCurrencyCZK string = "CZK" + + // CustomerBillCurrencyDJF captures enum value "DJF" + CustomerBillCurrencyDJF string = "DJF" + + // CustomerBillCurrencyDKK captures enum value "DKK" + CustomerBillCurrencyDKK string = "DKK" + + // CustomerBillCurrencyDOP captures enum value "DOP" + CustomerBillCurrencyDOP string = "DOP" + + // CustomerBillCurrencyDZD captures enum value "DZD" + CustomerBillCurrencyDZD string = "DZD" + + // CustomerBillCurrencyEGP captures enum value "EGP" + CustomerBillCurrencyEGP string = "EGP" + + // CustomerBillCurrencyERN captures enum value "ERN" + CustomerBillCurrencyERN string = "ERN" + + // CustomerBillCurrencyETB captures enum value "ETB" + CustomerBillCurrencyETB string = "ETB" + + // CustomerBillCurrencyEUR captures enum value "EUR" + CustomerBillCurrencyEUR string = "EUR" + + // CustomerBillCurrencyFJD captures enum value "FJD" + CustomerBillCurrencyFJD string = "FJD" + + // CustomerBillCurrencyFKP captures enum value "FKP" + CustomerBillCurrencyFKP string = "FKP" + + // CustomerBillCurrencyGBP captures enum value "GBP" + CustomerBillCurrencyGBP string = "GBP" + + // CustomerBillCurrencyGEL captures enum value "GEL" + CustomerBillCurrencyGEL string = "GEL" + + // CustomerBillCurrencyGHS captures enum value "GHS" + CustomerBillCurrencyGHS string = "GHS" + + // CustomerBillCurrencyGIP captures enum value "GIP" + CustomerBillCurrencyGIP string = "GIP" + + // CustomerBillCurrencyGMD captures enum value "GMD" + CustomerBillCurrencyGMD string = "GMD" + + // CustomerBillCurrencyGNF captures enum value "GNF" + CustomerBillCurrencyGNF string = "GNF" + + // CustomerBillCurrencyGTQ captures enum value "GTQ" + CustomerBillCurrencyGTQ string = "GTQ" + + // CustomerBillCurrencyGYD captures enum value "GYD" + CustomerBillCurrencyGYD string = "GYD" + + // CustomerBillCurrencyHKD captures enum value "HKD" + CustomerBillCurrencyHKD string = "HKD" + + // CustomerBillCurrencyHNL captures enum value "HNL" + CustomerBillCurrencyHNL string = "HNL" + + // CustomerBillCurrencyHRK captures enum value "HRK" + CustomerBillCurrencyHRK string = "HRK" + + // CustomerBillCurrencyHTG captures enum value "HTG" + CustomerBillCurrencyHTG string = "HTG" + + // CustomerBillCurrencyHUF captures enum value "HUF" + CustomerBillCurrencyHUF string = "HUF" + + // CustomerBillCurrencyIDR captures enum value "IDR" + CustomerBillCurrencyIDR string = "IDR" + + // CustomerBillCurrencyILS captures enum value "ILS" + CustomerBillCurrencyILS string = "ILS" + + // CustomerBillCurrencyINR captures enum value "INR" + CustomerBillCurrencyINR string = "INR" + + // CustomerBillCurrencyIQD captures enum value "IQD" + CustomerBillCurrencyIQD string = "IQD" + + // CustomerBillCurrencyIRR captures enum value "IRR" + CustomerBillCurrencyIRR string = "IRR" + + // CustomerBillCurrencyISK captures enum value "ISK" + CustomerBillCurrencyISK string = "ISK" + + // CustomerBillCurrencyJMD captures enum value "JMD" + CustomerBillCurrencyJMD string = "JMD" + + // CustomerBillCurrencyJOD captures enum value "JOD" + CustomerBillCurrencyJOD string = "JOD" + + // CustomerBillCurrencyJPY captures enum value "JPY" + CustomerBillCurrencyJPY string = "JPY" + + // CustomerBillCurrencyKES captures enum value "KES" + CustomerBillCurrencyKES string = "KES" + + // CustomerBillCurrencyKGS captures enum value "KGS" + CustomerBillCurrencyKGS string = "KGS" + + // CustomerBillCurrencyKHR captures enum value "KHR" + CustomerBillCurrencyKHR string = "KHR" + + // CustomerBillCurrencyKMF captures enum value "KMF" + CustomerBillCurrencyKMF string = "KMF" + + // CustomerBillCurrencyKPW captures enum value "KPW" + CustomerBillCurrencyKPW string = "KPW" + + // CustomerBillCurrencyKRW captures enum value "KRW" + CustomerBillCurrencyKRW string = "KRW" + + // CustomerBillCurrencyKWD captures enum value "KWD" + CustomerBillCurrencyKWD string = "KWD" + + // CustomerBillCurrencyKYD captures enum value "KYD" + CustomerBillCurrencyKYD string = "KYD" + + // CustomerBillCurrencyKZT captures enum value "KZT" + CustomerBillCurrencyKZT string = "KZT" + + // CustomerBillCurrencyLAK captures enum value "LAK" + CustomerBillCurrencyLAK string = "LAK" + + // CustomerBillCurrencyLBP captures enum value "LBP" + CustomerBillCurrencyLBP string = "LBP" + + // CustomerBillCurrencyLKR captures enum value "LKR" + CustomerBillCurrencyLKR string = "LKR" + + // CustomerBillCurrencyLRD captures enum value "LRD" + CustomerBillCurrencyLRD string = "LRD" + + // CustomerBillCurrencyLSL captures enum value "LSL" + CustomerBillCurrencyLSL string = "LSL" + + // CustomerBillCurrencyLYD captures enum value "LYD" + CustomerBillCurrencyLYD string = "LYD" + + // CustomerBillCurrencyMAD captures enum value "MAD" + CustomerBillCurrencyMAD string = "MAD" + + // CustomerBillCurrencyMDL captures enum value "MDL" + CustomerBillCurrencyMDL string = "MDL" + + // CustomerBillCurrencyMGA captures enum value "MGA" + CustomerBillCurrencyMGA string = "MGA" + + // CustomerBillCurrencyMKD captures enum value "MKD" + CustomerBillCurrencyMKD string = "MKD" + + // CustomerBillCurrencyMMK captures enum value "MMK" + CustomerBillCurrencyMMK string = "MMK" + + // CustomerBillCurrencyMNT captures enum value "MNT" + CustomerBillCurrencyMNT string = "MNT" + + // CustomerBillCurrencyMOP captures enum value "MOP" + CustomerBillCurrencyMOP string = "MOP" + + // CustomerBillCurrencyMRU captures enum value "MRU" + CustomerBillCurrencyMRU string = "MRU" + + // CustomerBillCurrencyMUR captures enum value "MUR" + CustomerBillCurrencyMUR string = "MUR" + + // CustomerBillCurrencyMVR captures enum value "MVR" + CustomerBillCurrencyMVR string = "MVR" + + // CustomerBillCurrencyMWK captures enum value "MWK" + CustomerBillCurrencyMWK string = "MWK" + + // CustomerBillCurrencyMXN captures enum value "MXN" + CustomerBillCurrencyMXN string = "MXN" + + // CustomerBillCurrencyMXV captures enum value "MXV" + CustomerBillCurrencyMXV string = "MXV" + + // CustomerBillCurrencyMYR captures enum value "MYR" + CustomerBillCurrencyMYR string = "MYR" + + // CustomerBillCurrencyMZN captures enum value "MZN" + CustomerBillCurrencyMZN string = "MZN" + + // CustomerBillCurrencyNAD captures enum value "NAD" + CustomerBillCurrencyNAD string = "NAD" + + // CustomerBillCurrencyNGN captures enum value "NGN" + CustomerBillCurrencyNGN string = "NGN" + + // CustomerBillCurrencyNIO captures enum value "NIO" + CustomerBillCurrencyNIO string = "NIO" + + // CustomerBillCurrencyNOK captures enum value "NOK" + CustomerBillCurrencyNOK string = "NOK" + + // CustomerBillCurrencyNPR captures enum value "NPR" + CustomerBillCurrencyNPR string = "NPR" + + // CustomerBillCurrencyNZD captures enum value "NZD" + CustomerBillCurrencyNZD string = "NZD" + + // CustomerBillCurrencyOMR captures enum value "OMR" + CustomerBillCurrencyOMR string = "OMR" + + // CustomerBillCurrencyPAB captures enum value "PAB" + CustomerBillCurrencyPAB string = "PAB" + + // CustomerBillCurrencyPEN captures enum value "PEN" + CustomerBillCurrencyPEN string = "PEN" + + // CustomerBillCurrencyPGK captures enum value "PGK" + CustomerBillCurrencyPGK string = "PGK" + + // CustomerBillCurrencyPHP captures enum value "PHP" + CustomerBillCurrencyPHP string = "PHP" + + // CustomerBillCurrencyPKR captures enum value "PKR" + CustomerBillCurrencyPKR string = "PKR" + + // CustomerBillCurrencyPLN captures enum value "PLN" + CustomerBillCurrencyPLN string = "PLN" + + // CustomerBillCurrencyPYG captures enum value "PYG" + CustomerBillCurrencyPYG string = "PYG" + + // CustomerBillCurrencyQAR captures enum value "QAR" + CustomerBillCurrencyQAR string = "QAR" + + // CustomerBillCurrencyRON captures enum value "RON" + CustomerBillCurrencyRON string = "RON" + + // CustomerBillCurrencyRSD captures enum value "RSD" + CustomerBillCurrencyRSD string = "RSD" + + // CustomerBillCurrencyRUB captures enum value "RUB" + CustomerBillCurrencyRUB string = "RUB" + + // CustomerBillCurrencyRWF captures enum value "RWF" + CustomerBillCurrencyRWF string = "RWF" + + // CustomerBillCurrencySAR captures enum value "SAR" + CustomerBillCurrencySAR string = "SAR" + + // CustomerBillCurrencySBD captures enum value "SBD" + CustomerBillCurrencySBD string = "SBD" + + // CustomerBillCurrencySCR captures enum value "SCR" + CustomerBillCurrencySCR string = "SCR" + + // CustomerBillCurrencySDG captures enum value "SDG" + CustomerBillCurrencySDG string = "SDG" + + // CustomerBillCurrencySEK captures enum value "SEK" + CustomerBillCurrencySEK string = "SEK" + + // CustomerBillCurrencySGD captures enum value "SGD" + CustomerBillCurrencySGD string = "SGD" + + // CustomerBillCurrencySHP captures enum value "SHP" + CustomerBillCurrencySHP string = "SHP" + + // CustomerBillCurrencySLL captures enum value "SLL" + CustomerBillCurrencySLL string = "SLL" + + // CustomerBillCurrencySOS captures enum value "SOS" + CustomerBillCurrencySOS string = "SOS" + + // CustomerBillCurrencySRD captures enum value "SRD" + CustomerBillCurrencySRD string = "SRD" + + // CustomerBillCurrencySSP captures enum value "SSP" + CustomerBillCurrencySSP string = "SSP" + + // CustomerBillCurrencySTN captures enum value "STN" + CustomerBillCurrencySTN string = "STN" + + // CustomerBillCurrencySVC captures enum value "SVC" + CustomerBillCurrencySVC string = "SVC" + + // CustomerBillCurrencySYP captures enum value "SYP" + CustomerBillCurrencySYP string = "SYP" + + // CustomerBillCurrencySZL captures enum value "SZL" + CustomerBillCurrencySZL string = "SZL" + + // CustomerBillCurrencyTHB captures enum value "THB" + CustomerBillCurrencyTHB string = "THB" + + // CustomerBillCurrencyTJS captures enum value "TJS" + CustomerBillCurrencyTJS string = "TJS" + + // CustomerBillCurrencyTMT captures enum value "TMT" + CustomerBillCurrencyTMT string = "TMT" + + // CustomerBillCurrencyTND captures enum value "TND" + CustomerBillCurrencyTND string = "TND" + + // CustomerBillCurrencyTOP captures enum value "TOP" + CustomerBillCurrencyTOP string = "TOP" + + // CustomerBillCurrencyTRY captures enum value "TRY" + CustomerBillCurrencyTRY string = "TRY" + + // CustomerBillCurrencyTTD captures enum value "TTD" + CustomerBillCurrencyTTD string = "TTD" + + // CustomerBillCurrencyTWD captures enum value "TWD" + CustomerBillCurrencyTWD string = "TWD" + + // CustomerBillCurrencyTZS captures enum value "TZS" + CustomerBillCurrencyTZS string = "TZS" + + // CustomerBillCurrencyUAH captures enum value "UAH" + CustomerBillCurrencyUAH string = "UAH" + + // CustomerBillCurrencyUGX captures enum value "UGX" + CustomerBillCurrencyUGX string = "UGX" + + // CustomerBillCurrencyUSD captures enum value "USD" + CustomerBillCurrencyUSD string = "USD" + + // CustomerBillCurrencyUSN captures enum value "USN" + CustomerBillCurrencyUSN string = "USN" + + // CustomerBillCurrencyUYI captures enum value "UYI" + CustomerBillCurrencyUYI string = "UYI" + + // CustomerBillCurrencyUYU captures enum value "UYU" + CustomerBillCurrencyUYU string = "UYU" + + // CustomerBillCurrencyUYW captures enum value "UYW" + CustomerBillCurrencyUYW string = "UYW" + + // CustomerBillCurrencyUZS captures enum value "UZS" + CustomerBillCurrencyUZS string = "UZS" + + // CustomerBillCurrencyVES captures enum value "VES" + CustomerBillCurrencyVES string = "VES" + + // CustomerBillCurrencyVND captures enum value "VND" + CustomerBillCurrencyVND string = "VND" + + // CustomerBillCurrencyVUV captures enum value "VUV" + CustomerBillCurrencyVUV string = "VUV" + + // CustomerBillCurrencyWST captures enum value "WST" + CustomerBillCurrencyWST string = "WST" + + // CustomerBillCurrencyXAF captures enum value "XAF" + CustomerBillCurrencyXAF string = "XAF" + + // CustomerBillCurrencyXAG captures enum value "XAG" + CustomerBillCurrencyXAG string = "XAG" + + // CustomerBillCurrencyXAU captures enum value "XAU" + CustomerBillCurrencyXAU string = "XAU" + + // CustomerBillCurrencyXBA captures enum value "XBA" + CustomerBillCurrencyXBA string = "XBA" + + // CustomerBillCurrencyXBB captures enum value "XBB" + CustomerBillCurrencyXBB string = "XBB" + + // CustomerBillCurrencyXBC captures enum value "XBC" + CustomerBillCurrencyXBC string = "XBC" + + // CustomerBillCurrencyXBD captures enum value "XBD" + CustomerBillCurrencyXBD string = "XBD" + + // CustomerBillCurrencyXCD captures enum value "XCD" + CustomerBillCurrencyXCD string = "XCD" + + // CustomerBillCurrencyXDR captures enum value "XDR" + CustomerBillCurrencyXDR string = "XDR" + + // CustomerBillCurrencyXOF captures enum value "XOF" + CustomerBillCurrencyXOF string = "XOF" + + // CustomerBillCurrencyXPD captures enum value "XPD" + CustomerBillCurrencyXPD string = "XPD" + + // CustomerBillCurrencyXPF captures enum value "XPF" + CustomerBillCurrencyXPF string = "XPF" + + // CustomerBillCurrencyXPT captures enum value "XPT" + CustomerBillCurrencyXPT string = "XPT" + + // CustomerBillCurrencyXSU captures enum value "XSU" + CustomerBillCurrencyXSU string = "XSU" + + // CustomerBillCurrencyXTS captures enum value "XTS" + CustomerBillCurrencyXTS string = "XTS" + + // CustomerBillCurrencyXUA captures enum value "XUA" + CustomerBillCurrencyXUA string = "XUA" + + // CustomerBillCurrencyXXX captures enum value "XXX" + CustomerBillCurrencyXXX string = "XXX" + + // CustomerBillCurrencyYER captures enum value "YER" + CustomerBillCurrencyYER string = "YER" + + // CustomerBillCurrencyZAR captures enum value "ZAR" + CustomerBillCurrencyZAR string = "ZAR" + + // CustomerBillCurrencyZMW captures enum value "ZMW" + CustomerBillCurrencyZMW string = "ZMW" + + // CustomerBillCurrencyZWL captures enum value "ZWL" + CustomerBillCurrencyZWL string = "ZWL" +) + +// prop value enum +func (m *Customer) validateBillCurrencyEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, customerTypeBillCurrencyPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Customer) validateBillCurrency(formats strfmt.Registry) error { + + if swag.IsZero(m.BillCurrency) { // not required + return nil + } + + // value enum + if err := m.validateBillCurrencyEnum("BillCurrency", "body", *m.BillCurrency); err != nil { + return err + } + + return nil +} + +var customerTypeBillPeriodPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["daily","weekly","bi-weekly","monthly","bi-monthly","quarterly","semi-annually","annually"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + customerTypeBillPeriodPropEnum = append(customerTypeBillPeriodPropEnum, v) + } +} + +const ( + + // CustomerBillPeriodDaily captures enum value "daily" + CustomerBillPeriodDaily string = "daily" + + // CustomerBillPeriodWeekly captures enum value "weekly" + CustomerBillPeriodWeekly string = "weekly" + + // CustomerBillPeriodBiWeekly captures enum value "bi-weekly" + CustomerBillPeriodBiWeekly string = "bi-weekly" + + // CustomerBillPeriodMonthly captures enum value "monthly" + CustomerBillPeriodMonthly string = "monthly" + + // CustomerBillPeriodBiMonthly captures enum value "bi-monthly" + CustomerBillPeriodBiMonthly string = "bi-monthly" + + // CustomerBillPeriodQuarterly captures enum value "quarterly" + CustomerBillPeriodQuarterly string = "quarterly" + + // CustomerBillPeriodSemiAnnually captures enum value "semi-annually" + CustomerBillPeriodSemiAnnually string = "semi-annually" + + // CustomerBillPeriodAnnually captures enum value "annually" + CustomerBillPeriodAnnually string = "annually" +) + +// prop value enum +func (m *Customer) validateBillPeriodEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, customerTypeBillPeriodPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Customer) validateBillPeriod(formats strfmt.Registry) error { + + if swag.IsZero(m.BillPeriod) { // not required + return nil + } + + // value enum + if err := m.validateBillPeriodEnum("BillPeriod", "body", *m.BillPeriod); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateCancelDate(formats strfmt.Registry) error { + + if swag.IsZero(m.CancelDate) { // not required + return nil + } + + if err := validate.FormatOf("CancelDate", "body", "date", m.CancelDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateContractEnd(formats strfmt.Registry) error { + + if swag.IsZero(m.ContractEnd) { // not required + return nil + } + + if err := validate.FormatOf("ContractEnd", "body", "date", m.ContractEnd.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateContractStart(formats strfmt.Registry) error { + + if swag.IsZero(m.ContractStart) { // not required + return nil + } + + if err := validate.FormatOf("ContractStart", "body", "date", m.ContractStart.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateDeletedAt(formats strfmt.Registry) error { + + if swag.IsZero(m.DeletedAt) { // not required + return nil + } + + if err := validate.FormatOf("DeletedAt", "body", "datetime", m.DeletedAt.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateEmailBcc(formats strfmt.Registry) error { + + if swag.IsZero(m.EmailBcc) { // not required + return nil + } + + if err := validate.FormatOf("EmailBcc", "body", "email", m.EmailBcc.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateEmailCc(formats strfmt.Registry) error { + + if swag.IsZero(m.EmailCc) { // not required + return nil + } + + if err := validate.FormatOf("EmailCc", "body", "email", m.EmailCc.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateEmailTo(formats strfmt.Registry) error { + + if swag.IsZero(m.EmailTo) { // not required + return nil + } + + if err := validate.FormatOf("EmailTo", "body", "email", m.EmailTo.String(), formats); err != nil { + return err + } + + return nil +} + +var customerTypeInvoiceModePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["email","post"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + customerTypeInvoiceModePropEnum = append(customerTypeInvoiceModePropEnum, v) + } +} + +const ( + + // CustomerInvoiceModeEmail captures enum value "email" + CustomerInvoiceModeEmail string = "email" + + // CustomerInvoiceModePost captures enum value "post" + CustomerInvoiceModePost string = "post" +) + +// prop value enum +func (m *Customer) validateInvoiceModeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, customerTypeInvoiceModePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Customer) validateInvoiceMode(formats strfmt.Registry) error { + + if swag.IsZero(m.InvoiceMode) { // not required + return nil + } + + // value enum + if err := m.validateInvoiceModeEnum("InvoiceMode", "body", *m.InvoiceMode); err != nil { + return err + } + + return nil +} + +var customerTypeLanguagePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["AA","AB","AE","AF","AK","AM","AN","AR","AS","AV","AY","AZ","BA","BE","BG","BH","BI","BM","BN","BO","BR","BS","CA","CE","CH","CO","CR","CS","CU","CV","CY","DA","DE","DV","DZ","EE","EL","EN","EO","ES","ET","EU","FA","FF","FI","FJ","FO","FR","FY","GA","GD","GL","GN","GU","GV","HA","HE","HI","HO","HR","HT","HU","HY","HZ","IA","ID","IE","IG","II","IK","IO","IS","IT","IU","JA","JV","KA","KG","KI","KJ","KK","KL","KM","KN","KO","KR","KS","KU","KV","KW","KY","LA","LB","LG","LI","LN","LO","LT","LU","LV","MG","MH","MI","MK","ML","MN","MR","MS","MT","MY","NA","NB","ND","NE","NG","NL","NN","NO","NR","NV","NY","OC","OJ","OM","OR","OS","PA","PI","PL","PS","PT","QU","RM","RN","RO","RU","RW","SA","SC","SD","SE","SG","SI","SK","SL","SM","SN","SO","SQ","SR","SS","ST","SU","SV","SW","TA","TE","TG","TH","TI","TK","TL","TN","TO","TR","TS","TT","TW","TY","UG","UK","UR","UZ","VE","VI","VO","WA","WO","XH","YI","YO","ZA","ZH","ZU"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + customerTypeLanguagePropEnum = append(customerTypeLanguagePropEnum, v) + } +} + +const ( + + // CustomerLanguageAA captures enum value "AA" + CustomerLanguageAA string = "AA" + + // CustomerLanguageAB captures enum value "AB" + CustomerLanguageAB string = "AB" + + // CustomerLanguageAE captures enum value "AE" + CustomerLanguageAE string = "AE" + + // CustomerLanguageAF captures enum value "AF" + CustomerLanguageAF string = "AF" + + // CustomerLanguageAK captures enum value "AK" + CustomerLanguageAK string = "AK" + + // CustomerLanguageAM captures enum value "AM" + CustomerLanguageAM string = "AM" + + // CustomerLanguageAN captures enum value "AN" + CustomerLanguageAN string = "AN" + + // CustomerLanguageAR captures enum value "AR" + CustomerLanguageAR string = "AR" + + // CustomerLanguageAS captures enum value "AS" + CustomerLanguageAS string = "AS" + + // CustomerLanguageAV captures enum value "AV" + CustomerLanguageAV string = "AV" + + // CustomerLanguageAY captures enum value "AY" + CustomerLanguageAY string = "AY" + + // CustomerLanguageAZ captures enum value "AZ" + CustomerLanguageAZ string = "AZ" + + // CustomerLanguageBA captures enum value "BA" + CustomerLanguageBA string = "BA" + + // CustomerLanguageBE captures enum value "BE" + CustomerLanguageBE string = "BE" + + // CustomerLanguageBG captures enum value "BG" + CustomerLanguageBG string = "BG" + + // CustomerLanguageBH captures enum value "BH" + CustomerLanguageBH string = "BH" + + // CustomerLanguageBI captures enum value "BI" + CustomerLanguageBI string = "BI" + + // CustomerLanguageBM captures enum value "BM" + CustomerLanguageBM string = "BM" + + // CustomerLanguageBN captures enum value "BN" + CustomerLanguageBN string = "BN" + + // CustomerLanguageBO captures enum value "BO" + CustomerLanguageBO string = "BO" + + // CustomerLanguageBR captures enum value "BR" + CustomerLanguageBR string = "BR" + + // CustomerLanguageBS captures enum value "BS" + CustomerLanguageBS string = "BS" + + // CustomerLanguageCA captures enum value "CA" + CustomerLanguageCA string = "CA" + + // CustomerLanguageCE captures enum value "CE" + CustomerLanguageCE string = "CE" + + // CustomerLanguageCH captures enum value "CH" + CustomerLanguageCH string = "CH" + + // CustomerLanguageCO captures enum value "CO" + CustomerLanguageCO string = "CO" + + // CustomerLanguageCR captures enum value "CR" + CustomerLanguageCR string = "CR" + + // CustomerLanguageCS captures enum value "CS" + CustomerLanguageCS string = "CS" + + // CustomerLanguageCU captures enum value "CU" + CustomerLanguageCU string = "CU" + + // CustomerLanguageCV captures enum value "CV" + CustomerLanguageCV string = "CV" + + // CustomerLanguageCY captures enum value "CY" + CustomerLanguageCY string = "CY" + + // CustomerLanguageDA captures enum value "DA" + CustomerLanguageDA string = "DA" + + // CustomerLanguageDE captures enum value "DE" + CustomerLanguageDE string = "DE" + + // CustomerLanguageDV captures enum value "DV" + CustomerLanguageDV string = "DV" + + // CustomerLanguageDZ captures enum value "DZ" + CustomerLanguageDZ string = "DZ" + + // CustomerLanguageEE captures enum value "EE" + CustomerLanguageEE string = "EE" + + // CustomerLanguageEL captures enum value "EL" + CustomerLanguageEL string = "EL" + + // CustomerLanguageEN captures enum value "EN" + CustomerLanguageEN string = "EN" + + // CustomerLanguageEO captures enum value "EO" + CustomerLanguageEO string = "EO" + + // CustomerLanguageES captures enum value "ES" + CustomerLanguageES string = "ES" + + // CustomerLanguageET captures enum value "ET" + CustomerLanguageET string = "ET" + + // CustomerLanguageEU captures enum value "EU" + CustomerLanguageEU string = "EU" + + // CustomerLanguageFA captures enum value "FA" + CustomerLanguageFA string = "FA" + + // CustomerLanguageFF captures enum value "FF" + CustomerLanguageFF string = "FF" + + // CustomerLanguageFI captures enum value "FI" + CustomerLanguageFI string = "FI" + + // CustomerLanguageFJ captures enum value "FJ" + CustomerLanguageFJ string = "FJ" + + // CustomerLanguageFO captures enum value "FO" + CustomerLanguageFO string = "FO" + + // CustomerLanguageFR captures enum value "FR" + CustomerLanguageFR string = "FR" + + // CustomerLanguageFY captures enum value "FY" + CustomerLanguageFY string = "FY" + + // CustomerLanguageGA captures enum value "GA" + CustomerLanguageGA string = "GA" + + // CustomerLanguageGD captures enum value "GD" + CustomerLanguageGD string = "GD" + + // CustomerLanguageGL captures enum value "GL" + CustomerLanguageGL string = "GL" + + // CustomerLanguageGN captures enum value "GN" + CustomerLanguageGN string = "GN" + + // CustomerLanguageGU captures enum value "GU" + CustomerLanguageGU string = "GU" + + // CustomerLanguageGV captures enum value "GV" + CustomerLanguageGV string = "GV" + + // CustomerLanguageHA captures enum value "HA" + CustomerLanguageHA string = "HA" + + // CustomerLanguageHE captures enum value "HE" + CustomerLanguageHE string = "HE" + + // CustomerLanguageHI captures enum value "HI" + CustomerLanguageHI string = "HI" + + // CustomerLanguageHO captures enum value "HO" + CustomerLanguageHO string = "HO" + + // CustomerLanguageHR captures enum value "HR" + CustomerLanguageHR string = "HR" + + // CustomerLanguageHT captures enum value "HT" + CustomerLanguageHT string = "HT" + + // CustomerLanguageHU captures enum value "HU" + CustomerLanguageHU string = "HU" + + // CustomerLanguageHY captures enum value "HY" + CustomerLanguageHY string = "HY" + + // CustomerLanguageHZ captures enum value "HZ" + CustomerLanguageHZ string = "HZ" + + // CustomerLanguageIA captures enum value "IA" + CustomerLanguageIA string = "IA" + + // CustomerLanguageID captures enum value "ID" + CustomerLanguageID string = "ID" + + // CustomerLanguageIE captures enum value "IE" + CustomerLanguageIE string = "IE" + + // CustomerLanguageIG captures enum value "IG" + CustomerLanguageIG string = "IG" + + // CustomerLanguageII captures enum value "II" + CustomerLanguageII string = "II" + + // CustomerLanguageIK captures enum value "IK" + CustomerLanguageIK string = "IK" + + // CustomerLanguageIO captures enum value "IO" + CustomerLanguageIO string = "IO" + + // CustomerLanguageIS captures enum value "IS" + CustomerLanguageIS string = "IS" + + // CustomerLanguageIT captures enum value "IT" + CustomerLanguageIT string = "IT" + + // CustomerLanguageIU captures enum value "IU" + CustomerLanguageIU string = "IU" + + // CustomerLanguageJA captures enum value "JA" + CustomerLanguageJA string = "JA" + + // CustomerLanguageJV captures enum value "JV" + CustomerLanguageJV string = "JV" + + // CustomerLanguageKA captures enum value "KA" + CustomerLanguageKA string = "KA" + + // CustomerLanguageKG captures enum value "KG" + CustomerLanguageKG string = "KG" + + // CustomerLanguageKI captures enum value "KI" + CustomerLanguageKI string = "KI" + + // CustomerLanguageKJ captures enum value "KJ" + CustomerLanguageKJ string = "KJ" + + // CustomerLanguageKK captures enum value "KK" + CustomerLanguageKK string = "KK" + + // CustomerLanguageKL captures enum value "KL" + CustomerLanguageKL string = "KL" + + // CustomerLanguageKM captures enum value "KM" + CustomerLanguageKM string = "KM" + + // CustomerLanguageKN captures enum value "KN" + CustomerLanguageKN string = "KN" + + // CustomerLanguageKO captures enum value "KO" + CustomerLanguageKO string = "KO" + + // CustomerLanguageKR captures enum value "KR" + CustomerLanguageKR string = "KR" + + // CustomerLanguageKS captures enum value "KS" + CustomerLanguageKS string = "KS" + + // CustomerLanguageKU captures enum value "KU" + CustomerLanguageKU string = "KU" + + // CustomerLanguageKV captures enum value "KV" + CustomerLanguageKV string = "KV" + + // CustomerLanguageKW captures enum value "KW" + CustomerLanguageKW string = "KW" + + // CustomerLanguageKY captures enum value "KY" + CustomerLanguageKY string = "KY" + + // CustomerLanguageLA captures enum value "LA" + CustomerLanguageLA string = "LA" + + // CustomerLanguageLB captures enum value "LB" + CustomerLanguageLB string = "LB" + + // CustomerLanguageLG captures enum value "LG" + CustomerLanguageLG string = "LG" + + // CustomerLanguageLI captures enum value "LI" + CustomerLanguageLI string = "LI" + + // CustomerLanguageLN captures enum value "LN" + CustomerLanguageLN string = "LN" + + // CustomerLanguageLO captures enum value "LO" + CustomerLanguageLO string = "LO" + + // CustomerLanguageLT captures enum value "LT" + CustomerLanguageLT string = "LT" + + // CustomerLanguageLU captures enum value "LU" + CustomerLanguageLU string = "LU" + + // CustomerLanguageLV captures enum value "LV" + CustomerLanguageLV string = "LV" + + // CustomerLanguageMG captures enum value "MG" + CustomerLanguageMG string = "MG" + + // CustomerLanguageMH captures enum value "MH" + CustomerLanguageMH string = "MH" + + // CustomerLanguageMI captures enum value "MI" + CustomerLanguageMI string = "MI" + + // CustomerLanguageMK captures enum value "MK" + CustomerLanguageMK string = "MK" + + // CustomerLanguageML captures enum value "ML" + CustomerLanguageML string = "ML" + + // CustomerLanguageMN captures enum value "MN" + CustomerLanguageMN string = "MN" + + // CustomerLanguageMR captures enum value "MR" + CustomerLanguageMR string = "MR" + + // CustomerLanguageMS captures enum value "MS" + CustomerLanguageMS string = "MS" + + // CustomerLanguageMT captures enum value "MT" + CustomerLanguageMT string = "MT" + + // CustomerLanguageMY captures enum value "MY" + CustomerLanguageMY string = "MY" + + // CustomerLanguageNA captures enum value "NA" + CustomerLanguageNA string = "NA" + + // CustomerLanguageNB captures enum value "NB" + CustomerLanguageNB string = "NB" + + // CustomerLanguageND captures enum value "ND" + CustomerLanguageND string = "ND" + + // CustomerLanguageNE captures enum value "NE" + CustomerLanguageNE string = "NE" + + // CustomerLanguageNG captures enum value "NG" + CustomerLanguageNG string = "NG" + + // CustomerLanguageNL captures enum value "NL" + CustomerLanguageNL string = "NL" + + // CustomerLanguageNN captures enum value "NN" + CustomerLanguageNN string = "NN" + + // CustomerLanguageNO captures enum value "NO" + CustomerLanguageNO string = "NO" + + // CustomerLanguageNR captures enum value "NR" + CustomerLanguageNR string = "NR" + + // CustomerLanguageNV captures enum value "NV" + CustomerLanguageNV string = "NV" + + // CustomerLanguageNY captures enum value "NY" + CustomerLanguageNY string = "NY" + + // CustomerLanguageOC captures enum value "OC" + CustomerLanguageOC string = "OC" + + // CustomerLanguageOJ captures enum value "OJ" + CustomerLanguageOJ string = "OJ" + + // CustomerLanguageOM captures enum value "OM" + CustomerLanguageOM string = "OM" + + // CustomerLanguageOR captures enum value "OR" + CustomerLanguageOR string = "OR" + + // CustomerLanguageOS captures enum value "OS" + CustomerLanguageOS string = "OS" + + // CustomerLanguagePA captures enum value "PA" + CustomerLanguagePA string = "PA" + + // CustomerLanguagePI captures enum value "PI" + CustomerLanguagePI string = "PI" + + // CustomerLanguagePL captures enum value "PL" + CustomerLanguagePL string = "PL" + + // CustomerLanguagePS captures enum value "PS" + CustomerLanguagePS string = "PS" + + // CustomerLanguagePT captures enum value "PT" + CustomerLanguagePT string = "PT" + + // CustomerLanguageQU captures enum value "QU" + CustomerLanguageQU string = "QU" + + // CustomerLanguageRM captures enum value "RM" + CustomerLanguageRM string = "RM" + + // CustomerLanguageRN captures enum value "RN" + CustomerLanguageRN string = "RN" + + // CustomerLanguageRO captures enum value "RO" + CustomerLanguageRO string = "RO" + + // CustomerLanguageRU captures enum value "RU" + CustomerLanguageRU string = "RU" + + // CustomerLanguageRW captures enum value "RW" + CustomerLanguageRW string = "RW" + + // CustomerLanguageSA captures enum value "SA" + CustomerLanguageSA string = "SA" + + // CustomerLanguageSC captures enum value "SC" + CustomerLanguageSC string = "SC" + + // CustomerLanguageSD captures enum value "SD" + CustomerLanguageSD string = "SD" + + // CustomerLanguageSE captures enum value "SE" + CustomerLanguageSE string = "SE" + + // CustomerLanguageSG captures enum value "SG" + CustomerLanguageSG string = "SG" + + // CustomerLanguageSI captures enum value "SI" + CustomerLanguageSI string = "SI" + + // CustomerLanguageSK captures enum value "SK" + CustomerLanguageSK string = "SK" + + // CustomerLanguageSL captures enum value "SL" + CustomerLanguageSL string = "SL" + + // CustomerLanguageSM captures enum value "SM" + CustomerLanguageSM string = "SM" + + // CustomerLanguageSN captures enum value "SN" + CustomerLanguageSN string = "SN" + + // CustomerLanguageSO captures enum value "SO" + CustomerLanguageSO string = "SO" + + // CustomerLanguageSQ captures enum value "SQ" + CustomerLanguageSQ string = "SQ" + + // CustomerLanguageSR captures enum value "SR" + CustomerLanguageSR string = "SR" + + // CustomerLanguageSS captures enum value "SS" + CustomerLanguageSS string = "SS" + + // CustomerLanguageST captures enum value "ST" + CustomerLanguageST string = "ST" + + // CustomerLanguageSU captures enum value "SU" + CustomerLanguageSU string = "SU" + + // CustomerLanguageSV captures enum value "SV" + CustomerLanguageSV string = "SV" + + // CustomerLanguageSW captures enum value "SW" + CustomerLanguageSW string = "SW" + + // CustomerLanguageTA captures enum value "TA" + CustomerLanguageTA string = "TA" + + // CustomerLanguageTE captures enum value "TE" + CustomerLanguageTE string = "TE" + + // CustomerLanguageTG captures enum value "TG" + CustomerLanguageTG string = "TG" + + // CustomerLanguageTH captures enum value "TH" + CustomerLanguageTH string = "TH" + + // CustomerLanguageTI captures enum value "TI" + CustomerLanguageTI string = "TI" + + // CustomerLanguageTK captures enum value "TK" + CustomerLanguageTK string = "TK" + + // CustomerLanguageTL captures enum value "TL" + CustomerLanguageTL string = "TL" + + // CustomerLanguageTN captures enum value "TN" + CustomerLanguageTN string = "TN" + + // CustomerLanguageTO captures enum value "TO" + CustomerLanguageTO string = "TO" + + // CustomerLanguageTR captures enum value "TR" + CustomerLanguageTR string = "TR" + + // CustomerLanguageTS captures enum value "TS" + CustomerLanguageTS string = "TS" + + // CustomerLanguageTT captures enum value "TT" + CustomerLanguageTT string = "TT" + + // CustomerLanguageTW captures enum value "TW" + CustomerLanguageTW string = "TW" + + // CustomerLanguageTY captures enum value "TY" + CustomerLanguageTY string = "TY" + + // CustomerLanguageUG captures enum value "UG" + CustomerLanguageUG string = "UG" + + // CustomerLanguageUK captures enum value "UK" + CustomerLanguageUK string = "UK" + + // CustomerLanguageUR captures enum value "UR" + CustomerLanguageUR string = "UR" + + // CustomerLanguageUZ captures enum value "UZ" + CustomerLanguageUZ string = "UZ" + + // CustomerLanguageVE captures enum value "VE" + CustomerLanguageVE string = "VE" + + // CustomerLanguageVI captures enum value "VI" + CustomerLanguageVI string = "VI" + + // CustomerLanguageVO captures enum value "VO" + CustomerLanguageVO string = "VO" + + // CustomerLanguageWA captures enum value "WA" + CustomerLanguageWA string = "WA" + + // CustomerLanguageWO captures enum value "WO" + CustomerLanguageWO string = "WO" + + // CustomerLanguageXH captures enum value "XH" + CustomerLanguageXH string = "XH" + + // CustomerLanguageYI captures enum value "YI" + CustomerLanguageYI string = "YI" + + // CustomerLanguageYO captures enum value "YO" + CustomerLanguageYO string = "YO" + + // CustomerLanguageZA captures enum value "ZA" + CustomerLanguageZA string = "ZA" + + // CustomerLanguageZH captures enum value "ZH" + CustomerLanguageZH string = "ZH" + + // CustomerLanguageZU captures enum value "ZU" + CustomerLanguageZU string = "ZU" +) + +// prop value enum +func (m *Customer) validateLanguageEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, customerTypeLanguagePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Customer) validateLanguage(formats strfmt.Registry) error { + + if swag.IsZero(m.Language) { // not required + return nil + } + + // value enum + if err := m.validateLanguageEnum("Language", "body", *m.Language); err != nil { + return err + } + + return nil +} + +func (m *Customer) validateProducts(formats strfmt.Registry) error { + + if swag.IsZero(m.Products) { // not required + return nil + } + + for i := 0; i < len(m.Products); i++ { + if swag.IsZero(m.Products[i]) { // not required + continue + } + + if m.Products[i] != nil { + if err := m.Products[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("Products" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Customer) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Customer) UnmarshalBinary(b []byte) error { + var res Customer + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/customerdb/models/error_response.go b/services/customerdb/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/services/customerdb/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/customerdb/models/item_created_response.go b/services/customerdb/models/item_created_response.go new file mode 100644 index 0000000..ea34934 --- /dev/null +++ b/services/customerdb/models/item_created_response.go @@ -0,0 +1,46 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ItemCreatedResponse item created response +// +// swagger:model ItemCreatedResponse +type ItemCreatedResponse struct { + + // Api link + APILink string `json:"ApiLink,omitempty"` + + // message + Message string `json:"Message,omitempty"` +} + +// Validate validates this item created response +func (m *ItemCreatedResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ItemCreatedResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ItemCreatedResponse) UnmarshalBinary(b []byte) error { + var res ItemCreatedResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/customerdb/models/product.go b/services/customerdb/models/product.go new file mode 100644 index 0000000..82f295d --- /dev/null +++ b/services/customerdb/models/product.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Product product +// +// swagger:model Product +type Product struct { + + // Api link + APILink string `json:"ApiLink,omitempty" gorm:"-"` + + // cancel date + // Format: date + CancelDate *strfmt.Date `json:"CancelDate,omitempty" gorm:"type:date;default:2100-12-31"` + + // customer Id + CustomerID string `json:"CustomerId,omitempty"` + + // deleted at + // Format: datetime + DeletedAt *strfmt.DateTime `json:"DeletedAt,omitempty" gorm:"type:timestamptz"` + + // discount + Discount float64 `json:"Discount,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // name + Name string `json:"Name,omitempty"` + + // plan Id + PlanID string `json:"PlanId,omitempty" gorm:"default:'DEFAULT'"` + + // product Id + ProductID string `json:"ProductId,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // type + Type string `json:"Type,omitempty"` +} + +// Validate validates this product +func (m *Product) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCancelDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeletedAt(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Product) validateCancelDate(formats strfmt.Registry) error { + + if swag.IsZero(m.CancelDate) { // not required + return nil + } + + if err := validate.FormatOf("CancelDate", "body", "date", m.CancelDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Product) validateDeletedAt(formats strfmt.Registry) error { + + if swag.IsZero(m.DeletedAt) { // not required + return nil + } + + if err := validate.FormatOf("DeletedAt", "body", "datetime", m.DeletedAt.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Product) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Product) UnmarshalBinary(b []byte) error { + var res Product + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/customerdb/models/reseller.go b/services/customerdb/models/reseller.go new file mode 100644 index 0000000..3e1b10e --- /dev/null +++ b/services/customerdb/models/reseller.go @@ -0,0 +1,1564 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Reseller reseller +// +// swagger:model Reseller +type Reseller struct { + + // abacus code + AbacusCode string `json:"AbacusCode,omitempty" gorm:"default:''"` + + // address + Address string `json:"Address,omitempty"` + + // Api link + APILink string `json:"ApiLink,omitempty" gorm:"-"` + + // bill contact + BillContact string `json:"BillContact,omitempty" gorm:"default:''"` + + // ISO-4217 currency code + // Enum: [AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BOV BRL BSD BTN BWP BYN BZD CAD CDF CHE CHF CHW CLF CLP CNY COP COU CRC CUC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HRK HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLL SOS SRD SSP STN SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD USN UYI UYU UYW UZS VES VND VUV WST XAF XAG XAU XBA XBB XBC XBD XCD XDR XOF XPD XPF XPT XSU XTS XUA XXX YER ZAR ZMW ZWL] + BillCurrency *string `json:"BillCurrency,omitempty" gorm:"default:CHF"` + + // bill period + // Enum: [daily weekly bi-weekly monthly bi-monthly quarterly semi-annually annually] + BillPeriod *string `json:"BillPeriod,omitempty" gorm:"default:monthly"` + + // billable + Billable *bool `json:"Billable,omitempty" gorm:"default:true"` + + // billing code + BillingCode string `json:"BillingCode,omitempty" gorm:"default:''"` + + // cancel date + // Format: date + CancelDate strfmt.Date `json:"CancelDate,omitempty" gorm:"type:date;default:2100-12-31"` + + // contract end + // Format: date + ContractEnd strfmt.Date `json:"ContractEnd,omitempty" gorm:"type:date;default:2030-12-31"` + + // contract start + // Format: date + ContractStart strfmt.Date `json:"ContractStart,omitempty" gorm:"type:date;default:2019-01-01"` + + // customers + Customers []*Customer `json:"Customers" gorm:"-"` + + // deleted at + // Format: datetime + DeletedAt *strfmt.DateTime `json:"DeletedAt,omitempty" gorm:"type:timestamptz"` + + // discount + Discount float64 `json:"Discount,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // email bcc + // Format: email + EmailBcc strfmt.Email `json:"EmailBcc,omitempty" gorm:"default:''"` + + // email cc + // Format: email + EmailCc strfmt.Email `json:"EmailCc,omitempty" gorm:"default:''"` + + // email to + // Format: email + EmailTo strfmt.Email `json:"EmailTo,omitempty" gorm:"default:''"` + + // invoice mode + // Enum: [email post] + InvoiceMode *string `json:"InvoiceMode,omitempty" gorm:"default:email"` + + // is active + IsActive *bool `json:"IsActive,omitempty" gorm:"default:true"` + + // ISO-369-1 alpha-2 language codes + // Enum: [AA AB AE AF AK AM AN AR AS AV AY AZ BA BE BG BH BI BM BN BO BR BS CA CE CH CO CR CS CU CV CY DA DE DV DZ EE EL EN EO ES ET EU FA FF FI FJ FO FR FY GA GD GL GN GU GV HA HE HI HO HR HT HU HY HZ IA ID IE IG II IK IO IS IT IU JA JV KA KG KI KJ KK KL KM KN KO KR KS KU KV KW KY LA LB LG LI LN LO LT LU LV MG MH MI MK ML MN MR MS MT MY NA NB ND NE NG NL NN NO NR NV NY OC OJ OM OR OS PA PI PL PS PT QU RM RN RO RU RW SA SC SD SE SG SI SK SL SM SN SO SQ SR SS ST SU SV SW TA TE TG TH TI TK TL TN TO TR TS TT TW TY UG UK UR UZ VE VI VO WA WO XH YI YO ZA ZH ZU] + Language *string `json:"Language,omitempty" gorm:"default:DE"` + + // name + Name string `json:"Name,omitempty"` + + // parent reseller Id + ParentResellerID string `json:"ParentResellerId,omitempty" gorm:"default:''"` + + // plan Id + PlanID string `json:"PlanId,omitempty" gorm:"default:'DEFAULT'"` + + // reseller Id + ResellerID string `json:"ResellerId,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` +} + +// Validate validates this reseller +func (m *Reseller) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBillCurrency(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBillPeriod(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCancelDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContractEnd(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContractStart(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCustomers(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDeletedAt(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmailBcc(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmailCc(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmailTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInvoiceMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLanguage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var resellerTypeBillCurrencyPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["AED","AFN","ALL","AMD","ANG","AOA","ARS","AUD","AWG","AZN","BAM","BBD","BDT","BGN","BHD","BIF","BMD","BND","BOB","BOV","BRL","BSD","BTN","BWP","BYN","BZD","CAD","CDF","CHE","CHF","CHW","CLF","CLP","CNY","COP","COU","CRC","CUC","CUP","CVE","CZK","DJF","DKK","DOP","DZD","EGP","ERN","ETB","EUR","FJD","FKP","GBP","GEL","GHS","GIP","GMD","GNF","GTQ","GYD","HKD","HNL","HRK","HTG","HUF","IDR","ILS","INR","IQD","IRR","ISK","JMD","JOD","JPY","KES","KGS","KHR","KMF","KPW","KRW","KWD","KYD","KZT","LAK","LBP","LKR","LRD","LSL","LYD","MAD","MDL","MGA","MKD","MMK","MNT","MOP","MRU","MUR","MVR","MWK","MXN","MXV","MYR","MZN","NAD","NGN","NIO","NOK","NPR","NZD","OMR","PAB","PEN","PGK","PHP","PKR","PLN","PYG","QAR","RON","RSD","RUB","RWF","SAR","SBD","SCR","SDG","SEK","SGD","SHP","SLL","SOS","SRD","SSP","STN","SVC","SYP","SZL","THB","TJS","TMT","TND","TOP","TRY","TTD","TWD","TZS","UAH","UGX","USD","USN","UYI","UYU","UYW","UZS","VES","VND","VUV","WST","XAF","XAG","XAU","XBA","XBB","XBC","XBD","XCD","XDR","XOF","XPD","XPF","XPT","XSU","XTS","XUA","XXX","YER","ZAR","ZMW","ZWL"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + resellerTypeBillCurrencyPropEnum = append(resellerTypeBillCurrencyPropEnum, v) + } +} + +const ( + + // ResellerBillCurrencyAED captures enum value "AED" + ResellerBillCurrencyAED string = "AED" + + // ResellerBillCurrencyAFN captures enum value "AFN" + ResellerBillCurrencyAFN string = "AFN" + + // ResellerBillCurrencyALL captures enum value "ALL" + ResellerBillCurrencyALL string = "ALL" + + // ResellerBillCurrencyAMD captures enum value "AMD" + ResellerBillCurrencyAMD string = "AMD" + + // ResellerBillCurrencyANG captures enum value "ANG" + ResellerBillCurrencyANG string = "ANG" + + // ResellerBillCurrencyAOA captures enum value "AOA" + ResellerBillCurrencyAOA string = "AOA" + + // ResellerBillCurrencyARS captures enum value "ARS" + ResellerBillCurrencyARS string = "ARS" + + // ResellerBillCurrencyAUD captures enum value "AUD" + ResellerBillCurrencyAUD string = "AUD" + + // ResellerBillCurrencyAWG captures enum value "AWG" + ResellerBillCurrencyAWG string = "AWG" + + // ResellerBillCurrencyAZN captures enum value "AZN" + ResellerBillCurrencyAZN string = "AZN" + + // ResellerBillCurrencyBAM captures enum value "BAM" + ResellerBillCurrencyBAM string = "BAM" + + // ResellerBillCurrencyBBD captures enum value "BBD" + ResellerBillCurrencyBBD string = "BBD" + + // ResellerBillCurrencyBDT captures enum value "BDT" + ResellerBillCurrencyBDT string = "BDT" + + // ResellerBillCurrencyBGN captures enum value "BGN" + ResellerBillCurrencyBGN string = "BGN" + + // ResellerBillCurrencyBHD captures enum value "BHD" + ResellerBillCurrencyBHD string = "BHD" + + // ResellerBillCurrencyBIF captures enum value "BIF" + ResellerBillCurrencyBIF string = "BIF" + + // ResellerBillCurrencyBMD captures enum value "BMD" + ResellerBillCurrencyBMD string = "BMD" + + // ResellerBillCurrencyBND captures enum value "BND" + ResellerBillCurrencyBND string = "BND" + + // ResellerBillCurrencyBOB captures enum value "BOB" + ResellerBillCurrencyBOB string = "BOB" + + // ResellerBillCurrencyBOV captures enum value "BOV" + ResellerBillCurrencyBOV string = "BOV" + + // ResellerBillCurrencyBRL captures enum value "BRL" + ResellerBillCurrencyBRL string = "BRL" + + // ResellerBillCurrencyBSD captures enum value "BSD" + ResellerBillCurrencyBSD string = "BSD" + + // ResellerBillCurrencyBTN captures enum value "BTN" + ResellerBillCurrencyBTN string = "BTN" + + // ResellerBillCurrencyBWP captures enum value "BWP" + ResellerBillCurrencyBWP string = "BWP" + + // ResellerBillCurrencyBYN captures enum value "BYN" + ResellerBillCurrencyBYN string = "BYN" + + // ResellerBillCurrencyBZD captures enum value "BZD" + ResellerBillCurrencyBZD string = "BZD" + + // ResellerBillCurrencyCAD captures enum value "CAD" + ResellerBillCurrencyCAD string = "CAD" + + // ResellerBillCurrencyCDF captures enum value "CDF" + ResellerBillCurrencyCDF string = "CDF" + + // ResellerBillCurrencyCHE captures enum value "CHE" + ResellerBillCurrencyCHE string = "CHE" + + // ResellerBillCurrencyCHF captures enum value "CHF" + ResellerBillCurrencyCHF string = "CHF" + + // ResellerBillCurrencyCHW captures enum value "CHW" + ResellerBillCurrencyCHW string = "CHW" + + // ResellerBillCurrencyCLF captures enum value "CLF" + ResellerBillCurrencyCLF string = "CLF" + + // ResellerBillCurrencyCLP captures enum value "CLP" + ResellerBillCurrencyCLP string = "CLP" + + // ResellerBillCurrencyCNY captures enum value "CNY" + ResellerBillCurrencyCNY string = "CNY" + + // ResellerBillCurrencyCOP captures enum value "COP" + ResellerBillCurrencyCOP string = "COP" + + // ResellerBillCurrencyCOU captures enum value "COU" + ResellerBillCurrencyCOU string = "COU" + + // ResellerBillCurrencyCRC captures enum value "CRC" + ResellerBillCurrencyCRC string = "CRC" + + // ResellerBillCurrencyCUC captures enum value "CUC" + ResellerBillCurrencyCUC string = "CUC" + + // ResellerBillCurrencyCUP captures enum value "CUP" + ResellerBillCurrencyCUP string = "CUP" + + // ResellerBillCurrencyCVE captures enum value "CVE" + ResellerBillCurrencyCVE string = "CVE" + + // ResellerBillCurrencyCZK captures enum value "CZK" + ResellerBillCurrencyCZK string = "CZK" + + // ResellerBillCurrencyDJF captures enum value "DJF" + ResellerBillCurrencyDJF string = "DJF" + + // ResellerBillCurrencyDKK captures enum value "DKK" + ResellerBillCurrencyDKK string = "DKK" + + // ResellerBillCurrencyDOP captures enum value "DOP" + ResellerBillCurrencyDOP string = "DOP" + + // ResellerBillCurrencyDZD captures enum value "DZD" + ResellerBillCurrencyDZD string = "DZD" + + // ResellerBillCurrencyEGP captures enum value "EGP" + ResellerBillCurrencyEGP string = "EGP" + + // ResellerBillCurrencyERN captures enum value "ERN" + ResellerBillCurrencyERN string = "ERN" + + // ResellerBillCurrencyETB captures enum value "ETB" + ResellerBillCurrencyETB string = "ETB" + + // ResellerBillCurrencyEUR captures enum value "EUR" + ResellerBillCurrencyEUR string = "EUR" + + // ResellerBillCurrencyFJD captures enum value "FJD" + ResellerBillCurrencyFJD string = "FJD" + + // ResellerBillCurrencyFKP captures enum value "FKP" + ResellerBillCurrencyFKP string = "FKP" + + // ResellerBillCurrencyGBP captures enum value "GBP" + ResellerBillCurrencyGBP string = "GBP" + + // ResellerBillCurrencyGEL captures enum value "GEL" + ResellerBillCurrencyGEL string = "GEL" + + // ResellerBillCurrencyGHS captures enum value "GHS" + ResellerBillCurrencyGHS string = "GHS" + + // ResellerBillCurrencyGIP captures enum value "GIP" + ResellerBillCurrencyGIP string = "GIP" + + // ResellerBillCurrencyGMD captures enum value "GMD" + ResellerBillCurrencyGMD string = "GMD" + + // ResellerBillCurrencyGNF captures enum value "GNF" + ResellerBillCurrencyGNF string = "GNF" + + // ResellerBillCurrencyGTQ captures enum value "GTQ" + ResellerBillCurrencyGTQ string = "GTQ" + + // ResellerBillCurrencyGYD captures enum value "GYD" + ResellerBillCurrencyGYD string = "GYD" + + // ResellerBillCurrencyHKD captures enum value "HKD" + ResellerBillCurrencyHKD string = "HKD" + + // ResellerBillCurrencyHNL captures enum value "HNL" + ResellerBillCurrencyHNL string = "HNL" + + // ResellerBillCurrencyHRK captures enum value "HRK" + ResellerBillCurrencyHRK string = "HRK" + + // ResellerBillCurrencyHTG captures enum value "HTG" + ResellerBillCurrencyHTG string = "HTG" + + // ResellerBillCurrencyHUF captures enum value "HUF" + ResellerBillCurrencyHUF string = "HUF" + + // ResellerBillCurrencyIDR captures enum value "IDR" + ResellerBillCurrencyIDR string = "IDR" + + // ResellerBillCurrencyILS captures enum value "ILS" + ResellerBillCurrencyILS string = "ILS" + + // ResellerBillCurrencyINR captures enum value "INR" + ResellerBillCurrencyINR string = "INR" + + // ResellerBillCurrencyIQD captures enum value "IQD" + ResellerBillCurrencyIQD string = "IQD" + + // ResellerBillCurrencyIRR captures enum value "IRR" + ResellerBillCurrencyIRR string = "IRR" + + // ResellerBillCurrencyISK captures enum value "ISK" + ResellerBillCurrencyISK string = "ISK" + + // ResellerBillCurrencyJMD captures enum value "JMD" + ResellerBillCurrencyJMD string = "JMD" + + // ResellerBillCurrencyJOD captures enum value "JOD" + ResellerBillCurrencyJOD string = "JOD" + + // ResellerBillCurrencyJPY captures enum value "JPY" + ResellerBillCurrencyJPY string = "JPY" + + // ResellerBillCurrencyKES captures enum value "KES" + ResellerBillCurrencyKES string = "KES" + + // ResellerBillCurrencyKGS captures enum value "KGS" + ResellerBillCurrencyKGS string = "KGS" + + // ResellerBillCurrencyKHR captures enum value "KHR" + ResellerBillCurrencyKHR string = "KHR" + + // ResellerBillCurrencyKMF captures enum value "KMF" + ResellerBillCurrencyKMF string = "KMF" + + // ResellerBillCurrencyKPW captures enum value "KPW" + ResellerBillCurrencyKPW string = "KPW" + + // ResellerBillCurrencyKRW captures enum value "KRW" + ResellerBillCurrencyKRW string = "KRW" + + // ResellerBillCurrencyKWD captures enum value "KWD" + ResellerBillCurrencyKWD string = "KWD" + + // ResellerBillCurrencyKYD captures enum value "KYD" + ResellerBillCurrencyKYD string = "KYD" + + // ResellerBillCurrencyKZT captures enum value "KZT" + ResellerBillCurrencyKZT string = "KZT" + + // ResellerBillCurrencyLAK captures enum value "LAK" + ResellerBillCurrencyLAK string = "LAK" + + // ResellerBillCurrencyLBP captures enum value "LBP" + ResellerBillCurrencyLBP string = "LBP" + + // ResellerBillCurrencyLKR captures enum value "LKR" + ResellerBillCurrencyLKR string = "LKR" + + // ResellerBillCurrencyLRD captures enum value "LRD" + ResellerBillCurrencyLRD string = "LRD" + + // ResellerBillCurrencyLSL captures enum value "LSL" + ResellerBillCurrencyLSL string = "LSL" + + // ResellerBillCurrencyLYD captures enum value "LYD" + ResellerBillCurrencyLYD string = "LYD" + + // ResellerBillCurrencyMAD captures enum value "MAD" + ResellerBillCurrencyMAD string = "MAD" + + // ResellerBillCurrencyMDL captures enum value "MDL" + ResellerBillCurrencyMDL string = "MDL" + + // ResellerBillCurrencyMGA captures enum value "MGA" + ResellerBillCurrencyMGA string = "MGA" + + // ResellerBillCurrencyMKD captures enum value "MKD" + ResellerBillCurrencyMKD string = "MKD" + + // ResellerBillCurrencyMMK captures enum value "MMK" + ResellerBillCurrencyMMK string = "MMK" + + // ResellerBillCurrencyMNT captures enum value "MNT" + ResellerBillCurrencyMNT string = "MNT" + + // ResellerBillCurrencyMOP captures enum value "MOP" + ResellerBillCurrencyMOP string = "MOP" + + // ResellerBillCurrencyMRU captures enum value "MRU" + ResellerBillCurrencyMRU string = "MRU" + + // ResellerBillCurrencyMUR captures enum value "MUR" + ResellerBillCurrencyMUR string = "MUR" + + // ResellerBillCurrencyMVR captures enum value "MVR" + ResellerBillCurrencyMVR string = "MVR" + + // ResellerBillCurrencyMWK captures enum value "MWK" + ResellerBillCurrencyMWK string = "MWK" + + // ResellerBillCurrencyMXN captures enum value "MXN" + ResellerBillCurrencyMXN string = "MXN" + + // ResellerBillCurrencyMXV captures enum value "MXV" + ResellerBillCurrencyMXV string = "MXV" + + // ResellerBillCurrencyMYR captures enum value "MYR" + ResellerBillCurrencyMYR string = "MYR" + + // ResellerBillCurrencyMZN captures enum value "MZN" + ResellerBillCurrencyMZN string = "MZN" + + // ResellerBillCurrencyNAD captures enum value "NAD" + ResellerBillCurrencyNAD string = "NAD" + + // ResellerBillCurrencyNGN captures enum value "NGN" + ResellerBillCurrencyNGN string = "NGN" + + // ResellerBillCurrencyNIO captures enum value "NIO" + ResellerBillCurrencyNIO string = "NIO" + + // ResellerBillCurrencyNOK captures enum value "NOK" + ResellerBillCurrencyNOK string = "NOK" + + // ResellerBillCurrencyNPR captures enum value "NPR" + ResellerBillCurrencyNPR string = "NPR" + + // ResellerBillCurrencyNZD captures enum value "NZD" + ResellerBillCurrencyNZD string = "NZD" + + // ResellerBillCurrencyOMR captures enum value "OMR" + ResellerBillCurrencyOMR string = "OMR" + + // ResellerBillCurrencyPAB captures enum value "PAB" + ResellerBillCurrencyPAB string = "PAB" + + // ResellerBillCurrencyPEN captures enum value "PEN" + ResellerBillCurrencyPEN string = "PEN" + + // ResellerBillCurrencyPGK captures enum value "PGK" + ResellerBillCurrencyPGK string = "PGK" + + // ResellerBillCurrencyPHP captures enum value "PHP" + ResellerBillCurrencyPHP string = "PHP" + + // ResellerBillCurrencyPKR captures enum value "PKR" + ResellerBillCurrencyPKR string = "PKR" + + // ResellerBillCurrencyPLN captures enum value "PLN" + ResellerBillCurrencyPLN string = "PLN" + + // ResellerBillCurrencyPYG captures enum value "PYG" + ResellerBillCurrencyPYG string = "PYG" + + // ResellerBillCurrencyQAR captures enum value "QAR" + ResellerBillCurrencyQAR string = "QAR" + + // ResellerBillCurrencyRON captures enum value "RON" + ResellerBillCurrencyRON string = "RON" + + // ResellerBillCurrencyRSD captures enum value "RSD" + ResellerBillCurrencyRSD string = "RSD" + + // ResellerBillCurrencyRUB captures enum value "RUB" + ResellerBillCurrencyRUB string = "RUB" + + // ResellerBillCurrencyRWF captures enum value "RWF" + ResellerBillCurrencyRWF string = "RWF" + + // ResellerBillCurrencySAR captures enum value "SAR" + ResellerBillCurrencySAR string = "SAR" + + // ResellerBillCurrencySBD captures enum value "SBD" + ResellerBillCurrencySBD string = "SBD" + + // ResellerBillCurrencySCR captures enum value "SCR" + ResellerBillCurrencySCR string = "SCR" + + // ResellerBillCurrencySDG captures enum value "SDG" + ResellerBillCurrencySDG string = "SDG" + + // ResellerBillCurrencySEK captures enum value "SEK" + ResellerBillCurrencySEK string = "SEK" + + // ResellerBillCurrencySGD captures enum value "SGD" + ResellerBillCurrencySGD string = "SGD" + + // ResellerBillCurrencySHP captures enum value "SHP" + ResellerBillCurrencySHP string = "SHP" + + // ResellerBillCurrencySLL captures enum value "SLL" + ResellerBillCurrencySLL string = "SLL" + + // ResellerBillCurrencySOS captures enum value "SOS" + ResellerBillCurrencySOS string = "SOS" + + // ResellerBillCurrencySRD captures enum value "SRD" + ResellerBillCurrencySRD string = "SRD" + + // ResellerBillCurrencySSP captures enum value "SSP" + ResellerBillCurrencySSP string = "SSP" + + // ResellerBillCurrencySTN captures enum value "STN" + ResellerBillCurrencySTN string = "STN" + + // ResellerBillCurrencySVC captures enum value "SVC" + ResellerBillCurrencySVC string = "SVC" + + // ResellerBillCurrencySYP captures enum value "SYP" + ResellerBillCurrencySYP string = "SYP" + + // ResellerBillCurrencySZL captures enum value "SZL" + ResellerBillCurrencySZL string = "SZL" + + // ResellerBillCurrencyTHB captures enum value "THB" + ResellerBillCurrencyTHB string = "THB" + + // ResellerBillCurrencyTJS captures enum value "TJS" + ResellerBillCurrencyTJS string = "TJS" + + // ResellerBillCurrencyTMT captures enum value "TMT" + ResellerBillCurrencyTMT string = "TMT" + + // ResellerBillCurrencyTND captures enum value "TND" + ResellerBillCurrencyTND string = "TND" + + // ResellerBillCurrencyTOP captures enum value "TOP" + ResellerBillCurrencyTOP string = "TOP" + + // ResellerBillCurrencyTRY captures enum value "TRY" + ResellerBillCurrencyTRY string = "TRY" + + // ResellerBillCurrencyTTD captures enum value "TTD" + ResellerBillCurrencyTTD string = "TTD" + + // ResellerBillCurrencyTWD captures enum value "TWD" + ResellerBillCurrencyTWD string = "TWD" + + // ResellerBillCurrencyTZS captures enum value "TZS" + ResellerBillCurrencyTZS string = "TZS" + + // ResellerBillCurrencyUAH captures enum value "UAH" + ResellerBillCurrencyUAH string = "UAH" + + // ResellerBillCurrencyUGX captures enum value "UGX" + ResellerBillCurrencyUGX string = "UGX" + + // ResellerBillCurrencyUSD captures enum value "USD" + ResellerBillCurrencyUSD string = "USD" + + // ResellerBillCurrencyUSN captures enum value "USN" + ResellerBillCurrencyUSN string = "USN" + + // ResellerBillCurrencyUYI captures enum value "UYI" + ResellerBillCurrencyUYI string = "UYI" + + // ResellerBillCurrencyUYU captures enum value "UYU" + ResellerBillCurrencyUYU string = "UYU" + + // ResellerBillCurrencyUYW captures enum value "UYW" + ResellerBillCurrencyUYW string = "UYW" + + // ResellerBillCurrencyUZS captures enum value "UZS" + ResellerBillCurrencyUZS string = "UZS" + + // ResellerBillCurrencyVES captures enum value "VES" + ResellerBillCurrencyVES string = "VES" + + // ResellerBillCurrencyVND captures enum value "VND" + ResellerBillCurrencyVND string = "VND" + + // ResellerBillCurrencyVUV captures enum value "VUV" + ResellerBillCurrencyVUV string = "VUV" + + // ResellerBillCurrencyWST captures enum value "WST" + ResellerBillCurrencyWST string = "WST" + + // ResellerBillCurrencyXAF captures enum value "XAF" + ResellerBillCurrencyXAF string = "XAF" + + // ResellerBillCurrencyXAG captures enum value "XAG" + ResellerBillCurrencyXAG string = "XAG" + + // ResellerBillCurrencyXAU captures enum value "XAU" + ResellerBillCurrencyXAU string = "XAU" + + // ResellerBillCurrencyXBA captures enum value "XBA" + ResellerBillCurrencyXBA string = "XBA" + + // ResellerBillCurrencyXBB captures enum value "XBB" + ResellerBillCurrencyXBB string = "XBB" + + // ResellerBillCurrencyXBC captures enum value "XBC" + ResellerBillCurrencyXBC string = "XBC" + + // ResellerBillCurrencyXBD captures enum value "XBD" + ResellerBillCurrencyXBD string = "XBD" + + // ResellerBillCurrencyXCD captures enum value "XCD" + ResellerBillCurrencyXCD string = "XCD" + + // ResellerBillCurrencyXDR captures enum value "XDR" + ResellerBillCurrencyXDR string = "XDR" + + // ResellerBillCurrencyXOF captures enum value "XOF" + ResellerBillCurrencyXOF string = "XOF" + + // ResellerBillCurrencyXPD captures enum value "XPD" + ResellerBillCurrencyXPD string = "XPD" + + // ResellerBillCurrencyXPF captures enum value "XPF" + ResellerBillCurrencyXPF string = "XPF" + + // ResellerBillCurrencyXPT captures enum value "XPT" + ResellerBillCurrencyXPT string = "XPT" + + // ResellerBillCurrencyXSU captures enum value "XSU" + ResellerBillCurrencyXSU string = "XSU" + + // ResellerBillCurrencyXTS captures enum value "XTS" + ResellerBillCurrencyXTS string = "XTS" + + // ResellerBillCurrencyXUA captures enum value "XUA" + ResellerBillCurrencyXUA string = "XUA" + + // ResellerBillCurrencyXXX captures enum value "XXX" + ResellerBillCurrencyXXX string = "XXX" + + // ResellerBillCurrencyYER captures enum value "YER" + ResellerBillCurrencyYER string = "YER" + + // ResellerBillCurrencyZAR captures enum value "ZAR" + ResellerBillCurrencyZAR string = "ZAR" + + // ResellerBillCurrencyZMW captures enum value "ZMW" + ResellerBillCurrencyZMW string = "ZMW" + + // ResellerBillCurrencyZWL captures enum value "ZWL" + ResellerBillCurrencyZWL string = "ZWL" +) + +// prop value enum +func (m *Reseller) validateBillCurrencyEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, resellerTypeBillCurrencyPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Reseller) validateBillCurrency(formats strfmt.Registry) error { + + if swag.IsZero(m.BillCurrency) { // not required + return nil + } + + // value enum + if err := m.validateBillCurrencyEnum("BillCurrency", "body", *m.BillCurrency); err != nil { + return err + } + + return nil +} + +var resellerTypeBillPeriodPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["daily","weekly","bi-weekly","monthly","bi-monthly","quarterly","semi-annually","annually"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + resellerTypeBillPeriodPropEnum = append(resellerTypeBillPeriodPropEnum, v) + } +} + +const ( + + // ResellerBillPeriodDaily captures enum value "daily" + ResellerBillPeriodDaily string = "daily" + + // ResellerBillPeriodWeekly captures enum value "weekly" + ResellerBillPeriodWeekly string = "weekly" + + // ResellerBillPeriodBiWeekly captures enum value "bi-weekly" + ResellerBillPeriodBiWeekly string = "bi-weekly" + + // ResellerBillPeriodMonthly captures enum value "monthly" + ResellerBillPeriodMonthly string = "monthly" + + // ResellerBillPeriodBiMonthly captures enum value "bi-monthly" + ResellerBillPeriodBiMonthly string = "bi-monthly" + + // ResellerBillPeriodQuarterly captures enum value "quarterly" + ResellerBillPeriodQuarterly string = "quarterly" + + // ResellerBillPeriodSemiAnnually captures enum value "semi-annually" + ResellerBillPeriodSemiAnnually string = "semi-annually" + + // ResellerBillPeriodAnnually captures enum value "annually" + ResellerBillPeriodAnnually string = "annually" +) + +// prop value enum +func (m *Reseller) validateBillPeriodEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, resellerTypeBillPeriodPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Reseller) validateBillPeriod(formats strfmt.Registry) error { + + if swag.IsZero(m.BillPeriod) { // not required + return nil + } + + // value enum + if err := m.validateBillPeriodEnum("BillPeriod", "body", *m.BillPeriod); err != nil { + return err + } + + return nil +} + +func (m *Reseller) validateCancelDate(formats strfmt.Registry) error { + + if swag.IsZero(m.CancelDate) { // not required + return nil + } + + if err := validate.FormatOf("CancelDate", "body", "date", m.CancelDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Reseller) validateContractEnd(formats strfmt.Registry) error { + + if swag.IsZero(m.ContractEnd) { // not required + return nil + } + + if err := validate.FormatOf("ContractEnd", "body", "date", m.ContractEnd.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Reseller) validateContractStart(formats strfmt.Registry) error { + + if swag.IsZero(m.ContractStart) { // not required + return nil + } + + if err := validate.FormatOf("ContractStart", "body", "date", m.ContractStart.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Reseller) validateCustomers(formats strfmt.Registry) error { + + if swag.IsZero(m.Customers) { // not required + return nil + } + + for i := 0; i < len(m.Customers); i++ { + if swag.IsZero(m.Customers[i]) { // not required + continue + } + + if m.Customers[i] != nil { + if err := m.Customers[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("Customers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *Reseller) validateDeletedAt(formats strfmt.Registry) error { + + if swag.IsZero(m.DeletedAt) { // not required + return nil + } + + if err := validate.FormatOf("DeletedAt", "body", "datetime", m.DeletedAt.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Reseller) validateEmailBcc(formats strfmt.Registry) error { + + if swag.IsZero(m.EmailBcc) { // not required + return nil + } + + if err := validate.FormatOf("EmailBcc", "body", "email", m.EmailBcc.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Reseller) validateEmailCc(formats strfmt.Registry) error { + + if swag.IsZero(m.EmailCc) { // not required + return nil + } + + if err := validate.FormatOf("EmailCc", "body", "email", m.EmailCc.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Reseller) validateEmailTo(formats strfmt.Registry) error { + + if swag.IsZero(m.EmailTo) { // not required + return nil + } + + if err := validate.FormatOf("EmailTo", "body", "email", m.EmailTo.String(), formats); err != nil { + return err + } + + return nil +} + +var resellerTypeInvoiceModePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["email","post"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + resellerTypeInvoiceModePropEnum = append(resellerTypeInvoiceModePropEnum, v) + } +} + +const ( + + // ResellerInvoiceModeEmail captures enum value "email" + ResellerInvoiceModeEmail string = "email" + + // ResellerInvoiceModePost captures enum value "post" + ResellerInvoiceModePost string = "post" +) + +// prop value enum +func (m *Reseller) validateInvoiceModeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, resellerTypeInvoiceModePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Reseller) validateInvoiceMode(formats strfmt.Registry) error { + + if swag.IsZero(m.InvoiceMode) { // not required + return nil + } + + // value enum + if err := m.validateInvoiceModeEnum("InvoiceMode", "body", *m.InvoiceMode); err != nil { + return err + } + + return nil +} + +var resellerTypeLanguagePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["AA","AB","AE","AF","AK","AM","AN","AR","AS","AV","AY","AZ","BA","BE","BG","BH","BI","BM","BN","BO","BR","BS","CA","CE","CH","CO","CR","CS","CU","CV","CY","DA","DE","DV","DZ","EE","EL","EN","EO","ES","ET","EU","FA","FF","FI","FJ","FO","FR","FY","GA","GD","GL","GN","GU","GV","HA","HE","HI","HO","HR","HT","HU","HY","HZ","IA","ID","IE","IG","II","IK","IO","IS","IT","IU","JA","JV","KA","KG","KI","KJ","KK","KL","KM","KN","KO","KR","KS","KU","KV","KW","KY","LA","LB","LG","LI","LN","LO","LT","LU","LV","MG","MH","MI","MK","ML","MN","MR","MS","MT","MY","NA","NB","ND","NE","NG","NL","NN","NO","NR","NV","NY","OC","OJ","OM","OR","OS","PA","PI","PL","PS","PT","QU","RM","RN","RO","RU","RW","SA","SC","SD","SE","SG","SI","SK","SL","SM","SN","SO","SQ","SR","SS","ST","SU","SV","SW","TA","TE","TG","TH","TI","TK","TL","TN","TO","TR","TS","TT","TW","TY","UG","UK","UR","UZ","VE","VI","VO","WA","WO","XH","YI","YO","ZA","ZH","ZU"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + resellerTypeLanguagePropEnum = append(resellerTypeLanguagePropEnum, v) + } +} + +const ( + + // ResellerLanguageAA captures enum value "AA" + ResellerLanguageAA string = "AA" + + // ResellerLanguageAB captures enum value "AB" + ResellerLanguageAB string = "AB" + + // ResellerLanguageAE captures enum value "AE" + ResellerLanguageAE string = "AE" + + // ResellerLanguageAF captures enum value "AF" + ResellerLanguageAF string = "AF" + + // ResellerLanguageAK captures enum value "AK" + ResellerLanguageAK string = "AK" + + // ResellerLanguageAM captures enum value "AM" + ResellerLanguageAM string = "AM" + + // ResellerLanguageAN captures enum value "AN" + ResellerLanguageAN string = "AN" + + // ResellerLanguageAR captures enum value "AR" + ResellerLanguageAR string = "AR" + + // ResellerLanguageAS captures enum value "AS" + ResellerLanguageAS string = "AS" + + // ResellerLanguageAV captures enum value "AV" + ResellerLanguageAV string = "AV" + + // ResellerLanguageAY captures enum value "AY" + ResellerLanguageAY string = "AY" + + // ResellerLanguageAZ captures enum value "AZ" + ResellerLanguageAZ string = "AZ" + + // ResellerLanguageBA captures enum value "BA" + ResellerLanguageBA string = "BA" + + // ResellerLanguageBE captures enum value "BE" + ResellerLanguageBE string = "BE" + + // ResellerLanguageBG captures enum value "BG" + ResellerLanguageBG string = "BG" + + // ResellerLanguageBH captures enum value "BH" + ResellerLanguageBH string = "BH" + + // ResellerLanguageBI captures enum value "BI" + ResellerLanguageBI string = "BI" + + // ResellerLanguageBM captures enum value "BM" + ResellerLanguageBM string = "BM" + + // ResellerLanguageBN captures enum value "BN" + ResellerLanguageBN string = "BN" + + // ResellerLanguageBO captures enum value "BO" + ResellerLanguageBO string = "BO" + + // ResellerLanguageBR captures enum value "BR" + ResellerLanguageBR string = "BR" + + // ResellerLanguageBS captures enum value "BS" + ResellerLanguageBS string = "BS" + + // ResellerLanguageCA captures enum value "CA" + ResellerLanguageCA string = "CA" + + // ResellerLanguageCE captures enum value "CE" + ResellerLanguageCE string = "CE" + + // ResellerLanguageCH captures enum value "CH" + ResellerLanguageCH string = "CH" + + // ResellerLanguageCO captures enum value "CO" + ResellerLanguageCO string = "CO" + + // ResellerLanguageCR captures enum value "CR" + ResellerLanguageCR string = "CR" + + // ResellerLanguageCS captures enum value "CS" + ResellerLanguageCS string = "CS" + + // ResellerLanguageCU captures enum value "CU" + ResellerLanguageCU string = "CU" + + // ResellerLanguageCV captures enum value "CV" + ResellerLanguageCV string = "CV" + + // ResellerLanguageCY captures enum value "CY" + ResellerLanguageCY string = "CY" + + // ResellerLanguageDA captures enum value "DA" + ResellerLanguageDA string = "DA" + + // ResellerLanguageDE captures enum value "DE" + ResellerLanguageDE string = "DE" + + // ResellerLanguageDV captures enum value "DV" + ResellerLanguageDV string = "DV" + + // ResellerLanguageDZ captures enum value "DZ" + ResellerLanguageDZ string = "DZ" + + // ResellerLanguageEE captures enum value "EE" + ResellerLanguageEE string = "EE" + + // ResellerLanguageEL captures enum value "EL" + ResellerLanguageEL string = "EL" + + // ResellerLanguageEN captures enum value "EN" + ResellerLanguageEN string = "EN" + + // ResellerLanguageEO captures enum value "EO" + ResellerLanguageEO string = "EO" + + // ResellerLanguageES captures enum value "ES" + ResellerLanguageES string = "ES" + + // ResellerLanguageET captures enum value "ET" + ResellerLanguageET string = "ET" + + // ResellerLanguageEU captures enum value "EU" + ResellerLanguageEU string = "EU" + + // ResellerLanguageFA captures enum value "FA" + ResellerLanguageFA string = "FA" + + // ResellerLanguageFF captures enum value "FF" + ResellerLanguageFF string = "FF" + + // ResellerLanguageFI captures enum value "FI" + ResellerLanguageFI string = "FI" + + // ResellerLanguageFJ captures enum value "FJ" + ResellerLanguageFJ string = "FJ" + + // ResellerLanguageFO captures enum value "FO" + ResellerLanguageFO string = "FO" + + // ResellerLanguageFR captures enum value "FR" + ResellerLanguageFR string = "FR" + + // ResellerLanguageFY captures enum value "FY" + ResellerLanguageFY string = "FY" + + // ResellerLanguageGA captures enum value "GA" + ResellerLanguageGA string = "GA" + + // ResellerLanguageGD captures enum value "GD" + ResellerLanguageGD string = "GD" + + // ResellerLanguageGL captures enum value "GL" + ResellerLanguageGL string = "GL" + + // ResellerLanguageGN captures enum value "GN" + ResellerLanguageGN string = "GN" + + // ResellerLanguageGU captures enum value "GU" + ResellerLanguageGU string = "GU" + + // ResellerLanguageGV captures enum value "GV" + ResellerLanguageGV string = "GV" + + // ResellerLanguageHA captures enum value "HA" + ResellerLanguageHA string = "HA" + + // ResellerLanguageHE captures enum value "HE" + ResellerLanguageHE string = "HE" + + // ResellerLanguageHI captures enum value "HI" + ResellerLanguageHI string = "HI" + + // ResellerLanguageHO captures enum value "HO" + ResellerLanguageHO string = "HO" + + // ResellerLanguageHR captures enum value "HR" + ResellerLanguageHR string = "HR" + + // ResellerLanguageHT captures enum value "HT" + ResellerLanguageHT string = "HT" + + // ResellerLanguageHU captures enum value "HU" + ResellerLanguageHU string = "HU" + + // ResellerLanguageHY captures enum value "HY" + ResellerLanguageHY string = "HY" + + // ResellerLanguageHZ captures enum value "HZ" + ResellerLanguageHZ string = "HZ" + + // ResellerLanguageIA captures enum value "IA" + ResellerLanguageIA string = "IA" + + // ResellerLanguageID captures enum value "ID" + ResellerLanguageID string = "ID" + + // ResellerLanguageIE captures enum value "IE" + ResellerLanguageIE string = "IE" + + // ResellerLanguageIG captures enum value "IG" + ResellerLanguageIG string = "IG" + + // ResellerLanguageII captures enum value "II" + ResellerLanguageII string = "II" + + // ResellerLanguageIK captures enum value "IK" + ResellerLanguageIK string = "IK" + + // ResellerLanguageIO captures enum value "IO" + ResellerLanguageIO string = "IO" + + // ResellerLanguageIS captures enum value "IS" + ResellerLanguageIS string = "IS" + + // ResellerLanguageIT captures enum value "IT" + ResellerLanguageIT string = "IT" + + // ResellerLanguageIU captures enum value "IU" + ResellerLanguageIU string = "IU" + + // ResellerLanguageJA captures enum value "JA" + ResellerLanguageJA string = "JA" + + // ResellerLanguageJV captures enum value "JV" + ResellerLanguageJV string = "JV" + + // ResellerLanguageKA captures enum value "KA" + ResellerLanguageKA string = "KA" + + // ResellerLanguageKG captures enum value "KG" + ResellerLanguageKG string = "KG" + + // ResellerLanguageKI captures enum value "KI" + ResellerLanguageKI string = "KI" + + // ResellerLanguageKJ captures enum value "KJ" + ResellerLanguageKJ string = "KJ" + + // ResellerLanguageKK captures enum value "KK" + ResellerLanguageKK string = "KK" + + // ResellerLanguageKL captures enum value "KL" + ResellerLanguageKL string = "KL" + + // ResellerLanguageKM captures enum value "KM" + ResellerLanguageKM string = "KM" + + // ResellerLanguageKN captures enum value "KN" + ResellerLanguageKN string = "KN" + + // ResellerLanguageKO captures enum value "KO" + ResellerLanguageKO string = "KO" + + // ResellerLanguageKR captures enum value "KR" + ResellerLanguageKR string = "KR" + + // ResellerLanguageKS captures enum value "KS" + ResellerLanguageKS string = "KS" + + // ResellerLanguageKU captures enum value "KU" + ResellerLanguageKU string = "KU" + + // ResellerLanguageKV captures enum value "KV" + ResellerLanguageKV string = "KV" + + // ResellerLanguageKW captures enum value "KW" + ResellerLanguageKW string = "KW" + + // ResellerLanguageKY captures enum value "KY" + ResellerLanguageKY string = "KY" + + // ResellerLanguageLA captures enum value "LA" + ResellerLanguageLA string = "LA" + + // ResellerLanguageLB captures enum value "LB" + ResellerLanguageLB string = "LB" + + // ResellerLanguageLG captures enum value "LG" + ResellerLanguageLG string = "LG" + + // ResellerLanguageLI captures enum value "LI" + ResellerLanguageLI string = "LI" + + // ResellerLanguageLN captures enum value "LN" + ResellerLanguageLN string = "LN" + + // ResellerLanguageLO captures enum value "LO" + ResellerLanguageLO string = "LO" + + // ResellerLanguageLT captures enum value "LT" + ResellerLanguageLT string = "LT" + + // ResellerLanguageLU captures enum value "LU" + ResellerLanguageLU string = "LU" + + // ResellerLanguageLV captures enum value "LV" + ResellerLanguageLV string = "LV" + + // ResellerLanguageMG captures enum value "MG" + ResellerLanguageMG string = "MG" + + // ResellerLanguageMH captures enum value "MH" + ResellerLanguageMH string = "MH" + + // ResellerLanguageMI captures enum value "MI" + ResellerLanguageMI string = "MI" + + // ResellerLanguageMK captures enum value "MK" + ResellerLanguageMK string = "MK" + + // ResellerLanguageML captures enum value "ML" + ResellerLanguageML string = "ML" + + // ResellerLanguageMN captures enum value "MN" + ResellerLanguageMN string = "MN" + + // ResellerLanguageMR captures enum value "MR" + ResellerLanguageMR string = "MR" + + // ResellerLanguageMS captures enum value "MS" + ResellerLanguageMS string = "MS" + + // ResellerLanguageMT captures enum value "MT" + ResellerLanguageMT string = "MT" + + // ResellerLanguageMY captures enum value "MY" + ResellerLanguageMY string = "MY" + + // ResellerLanguageNA captures enum value "NA" + ResellerLanguageNA string = "NA" + + // ResellerLanguageNB captures enum value "NB" + ResellerLanguageNB string = "NB" + + // ResellerLanguageND captures enum value "ND" + ResellerLanguageND string = "ND" + + // ResellerLanguageNE captures enum value "NE" + ResellerLanguageNE string = "NE" + + // ResellerLanguageNG captures enum value "NG" + ResellerLanguageNG string = "NG" + + // ResellerLanguageNL captures enum value "NL" + ResellerLanguageNL string = "NL" + + // ResellerLanguageNN captures enum value "NN" + ResellerLanguageNN string = "NN" + + // ResellerLanguageNO captures enum value "NO" + ResellerLanguageNO string = "NO" + + // ResellerLanguageNR captures enum value "NR" + ResellerLanguageNR string = "NR" + + // ResellerLanguageNV captures enum value "NV" + ResellerLanguageNV string = "NV" + + // ResellerLanguageNY captures enum value "NY" + ResellerLanguageNY string = "NY" + + // ResellerLanguageOC captures enum value "OC" + ResellerLanguageOC string = "OC" + + // ResellerLanguageOJ captures enum value "OJ" + ResellerLanguageOJ string = "OJ" + + // ResellerLanguageOM captures enum value "OM" + ResellerLanguageOM string = "OM" + + // ResellerLanguageOR captures enum value "OR" + ResellerLanguageOR string = "OR" + + // ResellerLanguageOS captures enum value "OS" + ResellerLanguageOS string = "OS" + + // ResellerLanguagePA captures enum value "PA" + ResellerLanguagePA string = "PA" + + // ResellerLanguagePI captures enum value "PI" + ResellerLanguagePI string = "PI" + + // ResellerLanguagePL captures enum value "PL" + ResellerLanguagePL string = "PL" + + // ResellerLanguagePS captures enum value "PS" + ResellerLanguagePS string = "PS" + + // ResellerLanguagePT captures enum value "PT" + ResellerLanguagePT string = "PT" + + // ResellerLanguageQU captures enum value "QU" + ResellerLanguageQU string = "QU" + + // ResellerLanguageRM captures enum value "RM" + ResellerLanguageRM string = "RM" + + // ResellerLanguageRN captures enum value "RN" + ResellerLanguageRN string = "RN" + + // ResellerLanguageRO captures enum value "RO" + ResellerLanguageRO string = "RO" + + // ResellerLanguageRU captures enum value "RU" + ResellerLanguageRU string = "RU" + + // ResellerLanguageRW captures enum value "RW" + ResellerLanguageRW string = "RW" + + // ResellerLanguageSA captures enum value "SA" + ResellerLanguageSA string = "SA" + + // ResellerLanguageSC captures enum value "SC" + ResellerLanguageSC string = "SC" + + // ResellerLanguageSD captures enum value "SD" + ResellerLanguageSD string = "SD" + + // ResellerLanguageSE captures enum value "SE" + ResellerLanguageSE string = "SE" + + // ResellerLanguageSG captures enum value "SG" + ResellerLanguageSG string = "SG" + + // ResellerLanguageSI captures enum value "SI" + ResellerLanguageSI string = "SI" + + // ResellerLanguageSK captures enum value "SK" + ResellerLanguageSK string = "SK" + + // ResellerLanguageSL captures enum value "SL" + ResellerLanguageSL string = "SL" + + // ResellerLanguageSM captures enum value "SM" + ResellerLanguageSM string = "SM" + + // ResellerLanguageSN captures enum value "SN" + ResellerLanguageSN string = "SN" + + // ResellerLanguageSO captures enum value "SO" + ResellerLanguageSO string = "SO" + + // ResellerLanguageSQ captures enum value "SQ" + ResellerLanguageSQ string = "SQ" + + // ResellerLanguageSR captures enum value "SR" + ResellerLanguageSR string = "SR" + + // ResellerLanguageSS captures enum value "SS" + ResellerLanguageSS string = "SS" + + // ResellerLanguageST captures enum value "ST" + ResellerLanguageST string = "ST" + + // ResellerLanguageSU captures enum value "SU" + ResellerLanguageSU string = "SU" + + // ResellerLanguageSV captures enum value "SV" + ResellerLanguageSV string = "SV" + + // ResellerLanguageSW captures enum value "SW" + ResellerLanguageSW string = "SW" + + // ResellerLanguageTA captures enum value "TA" + ResellerLanguageTA string = "TA" + + // ResellerLanguageTE captures enum value "TE" + ResellerLanguageTE string = "TE" + + // ResellerLanguageTG captures enum value "TG" + ResellerLanguageTG string = "TG" + + // ResellerLanguageTH captures enum value "TH" + ResellerLanguageTH string = "TH" + + // ResellerLanguageTI captures enum value "TI" + ResellerLanguageTI string = "TI" + + // ResellerLanguageTK captures enum value "TK" + ResellerLanguageTK string = "TK" + + // ResellerLanguageTL captures enum value "TL" + ResellerLanguageTL string = "TL" + + // ResellerLanguageTN captures enum value "TN" + ResellerLanguageTN string = "TN" + + // ResellerLanguageTO captures enum value "TO" + ResellerLanguageTO string = "TO" + + // ResellerLanguageTR captures enum value "TR" + ResellerLanguageTR string = "TR" + + // ResellerLanguageTS captures enum value "TS" + ResellerLanguageTS string = "TS" + + // ResellerLanguageTT captures enum value "TT" + ResellerLanguageTT string = "TT" + + // ResellerLanguageTW captures enum value "TW" + ResellerLanguageTW string = "TW" + + // ResellerLanguageTY captures enum value "TY" + ResellerLanguageTY string = "TY" + + // ResellerLanguageUG captures enum value "UG" + ResellerLanguageUG string = "UG" + + // ResellerLanguageUK captures enum value "UK" + ResellerLanguageUK string = "UK" + + // ResellerLanguageUR captures enum value "UR" + ResellerLanguageUR string = "UR" + + // ResellerLanguageUZ captures enum value "UZ" + ResellerLanguageUZ string = "UZ" + + // ResellerLanguageVE captures enum value "VE" + ResellerLanguageVE string = "VE" + + // ResellerLanguageVI captures enum value "VI" + ResellerLanguageVI string = "VI" + + // ResellerLanguageVO captures enum value "VO" + ResellerLanguageVO string = "VO" + + // ResellerLanguageWA captures enum value "WA" + ResellerLanguageWA string = "WA" + + // ResellerLanguageWO captures enum value "WO" + ResellerLanguageWO string = "WO" + + // ResellerLanguageXH captures enum value "XH" + ResellerLanguageXH string = "XH" + + // ResellerLanguageYI captures enum value "YI" + ResellerLanguageYI string = "YI" + + // ResellerLanguageYO captures enum value "YO" + ResellerLanguageYO string = "YO" + + // ResellerLanguageZA captures enum value "ZA" + ResellerLanguageZA string = "ZA" + + // ResellerLanguageZH captures enum value "ZH" + ResellerLanguageZH string = "ZH" + + // ResellerLanguageZU captures enum value "ZU" + ResellerLanguageZU string = "ZU" +) + +// prop value enum +func (m *Reseller) validateLanguageEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, resellerTypeLanguagePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Reseller) validateLanguage(formats strfmt.Registry) error { + + if swag.IsZero(m.Language) { // not required + return nil + } + + // value enum + if err := m.validateLanguageEnum("Language", "body", *m.Language); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Reseller) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Reseller) UnmarshalBinary(b []byte) error { + var res Reseller + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/customerdb/models/status.go b/services/customerdb/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/services/customerdb/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/customerdb/restapi/configure_customer_database_management.go b/services/customerdb/restapi/configure_customer_database_management.go new file mode 100644 index 0000000..47e1fb6 --- /dev/null +++ b/services/customerdb/restapi/configure_customer_database_management.go @@ -0,0 +1,265 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/customer_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/product_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/reseller_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/trigger_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name CustomerManagementAPI -inpkg + +/* CustomerManagementAPI */ +type CustomerManagementAPI interface { + /* AddCustomer Insert a new customer in the system. */ + AddCustomer(ctx context.Context, params customer_management.AddCustomerParams) middleware.Responder + + /* GetCustomer Return the information about the customer with the given id */ + GetCustomer(ctx context.Context, params customer_management.GetCustomerParams) middleware.Responder + + /* ListCustomers List all the customers in the system */ + ListCustomers(ctx context.Context, params customer_management.ListCustomersParams) middleware.Responder + + /* UpdateCustomer Updates the information of the customer with the given id */ + UpdateCustomer(ctx context.Context, params customer_management.UpdateCustomerParams) middleware.Responder +} + +//go:generate mockery -name ProductManagementAPI -inpkg + +/* ProductManagementAPI */ +type ProductManagementAPI interface { + /* AddProduct Insert a new product in the system. */ + AddProduct(ctx context.Context, params product_management.AddProductParams) middleware.Responder + + /* GetProduct Return the information about the product with the given id */ + GetProduct(ctx context.Context, params product_management.GetProductParams) middleware.Responder + + /* ListProducts List all the products in the system */ + ListProducts(ctx context.Context, params product_management.ListProductsParams) middleware.Responder + + /* UpdateProduct Updates the information of the product with the given id */ + UpdateProduct(ctx context.Context, params product_management.UpdateProductParams) middleware.Responder +} + +//go:generate mockery -name ResellerManagementAPI -inpkg + +/* ResellerManagementAPI */ +type ResellerManagementAPI interface { + /* AddReseller Insert a new reseller in the system. */ + AddReseller(ctx context.Context, params reseller_management.AddResellerParams) middleware.Responder + + /* GetReseller Return the information about the reseller with the given id */ + GetReseller(ctx context.Context, params reseller_management.GetResellerParams) middleware.Responder + + /* ListResellers List all the resellers in the system */ + ListResellers(ctx context.Context, params reseller_management.ListResellersParams) middleware.Responder + + /* UpdateReseller Updates the information of the reseller with the given id */ + UpdateReseller(ctx context.Context, params reseller_management.UpdateResellerParams) middleware.Responder +} + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* ExecSample Sample task trigger */ + ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + CustomerManagementAPI + ProductManagementAPI + ResellerManagementAPI + StatusManagementAPI + TriggerManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *CustomerDatabaseManagement instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.CustomerDatabaseManagementAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewCustomerDatabaseManagementAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.CustomerManagementAddCustomerHandler = customer_management.AddCustomerHandlerFunc(func(params customer_management.AddCustomerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CustomerManagementAPI.AddCustomer(ctx, params) + }) + api.ProductManagementAddProductHandler = product_management.AddProductHandlerFunc(func(params product_management.AddProductParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ProductManagementAPI.AddProduct(ctx, params) + }) + api.ResellerManagementAddResellerHandler = reseller_management.AddResellerHandlerFunc(func(params reseller_management.AddResellerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ResellerManagementAPI.AddReseller(ctx, params) + }) + api.TriggerManagementExecSampleHandler = trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.ExecSample(ctx, params) + }) + api.CustomerManagementGetCustomerHandler = customer_management.GetCustomerHandlerFunc(func(params customer_management.GetCustomerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CustomerManagementAPI.GetCustomer(ctx, params) + }) + api.ProductManagementGetProductHandler = product_management.GetProductHandlerFunc(func(params product_management.GetProductParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ProductManagementAPI.GetProduct(ctx, params) + }) + api.ResellerManagementGetResellerHandler = reseller_management.GetResellerHandlerFunc(func(params reseller_management.GetResellerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ResellerManagementAPI.GetReseller(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.CustomerManagementListCustomersHandler = customer_management.ListCustomersHandlerFunc(func(params customer_management.ListCustomersParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CustomerManagementAPI.ListCustomers(ctx, params) + }) + api.ProductManagementListProductsHandler = product_management.ListProductsHandlerFunc(func(params product_management.ListProductsParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ProductManagementAPI.ListProducts(ctx, params) + }) + api.ResellerManagementListResellersHandler = reseller_management.ListResellersHandlerFunc(func(params reseller_management.ListResellersParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ResellerManagementAPI.ListResellers(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.CustomerManagementUpdateCustomerHandler = customer_management.UpdateCustomerHandlerFunc(func(params customer_management.UpdateCustomerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CustomerManagementAPI.UpdateCustomer(ctx, params) + }) + api.ProductManagementUpdateProductHandler = product_management.UpdateProductHandlerFunc(func(params product_management.UpdateProductParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ProductManagementAPI.UpdateProduct(ctx, params) + }) + api.ResellerManagementUpdateResellerHandler = reseller_management.UpdateResellerHandlerFunc(func(params reseller_management.UpdateResellerParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.ResellerManagementAPI.UpdateReseller(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/services/customerdb/restapi/doc.go b/services/customerdb/restapi/doc.go new file mode 100644 index 0000000..484e4d1 --- /dev/null +++ b/services/customerdb/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi Customer Database Management API +// +// An API which supports creation, deletion, listing etc of customers and products +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v1.0 +// Version: 1.0.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/services/customerdb/restapi/embedded_spec.go b/services/customerdb/restapi/embedded_spec.go new file mode 100644 index 0000000..7a59501 --- /dev/null +++ b/services/customerdb/restapi/embedded_spec.go @@ -0,0 +1,4004 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of customers and products", + "title": "Customer Database Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/customer": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "List all the customers in the system", + "operationId": "listCustomers", + "responses": { + "200": { + "description": "List of customers in the system returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Customer" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "Insert a new customer in the system.", + "operationId": "addCustomer", + "parameters": [ + { + "description": "Customer to be added", + "name": "customer", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Customer" + } + } + ], + "responses": { + "201": { + "description": "New customer was added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The new customer was added but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "409": { + "description": "The given item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/customer/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "Return the information about the customer with the given id", + "operationId": "getCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the customer to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Customer with the id given in the system returned", + "schema": { + "$ref": "#/definitions/Customer" + } + }, + "404": { + "description": "The customer with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "Updates the information of the customer with the given id", + "operationId": "updateCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the customer to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Customer to be updated", + "name": "customer", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Customer" + } + } + ], + "responses": { + "200": { + "description": "Customer with the given id was updated", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The customer was updated but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The customer with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/product": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "List all the products in the system", + "operationId": "listProducts", + "responses": { + "200": { + "description": "List of products in the system returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Product" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "Insert a new product in the system.", + "operationId": "addProduct", + "parameters": [ + { + "description": "Product to be added", + "name": "product", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Product" + } + } + ], + "responses": { + "201": { + "description": "New product was added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "409": { + "description": "The given item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/product/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "Return the information about the product with the given id", + "operationId": "getProduct", + "parameters": [ + { + "type": "string", + "description": "Id of the product to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Product with the id given in the system returned", + "schema": { + "$ref": "#/definitions/Product" + } + }, + "404": { + "description": "The product with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "Updates the information of the product with the given id", + "operationId": "updateProduct", + "parameters": [ + { + "type": "string", + "description": "Id of the product to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Product to be updated", + "name": "product", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Product" + } + } + ], + "responses": { + "200": { + "description": "Product with the given id was updated", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The product with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/reseller": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "List all the resellers in the system", + "operationId": "listResellers", + "responses": { + "200": { + "description": "List of resellers in the system returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Reseller" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "Insert a new reseller in the system.", + "operationId": "addReseller", + "parameters": [ + { + "description": "Reseller to be added", + "name": "reseller", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Reseller" + } + } + ], + "responses": { + "201": { + "description": "New reseller was added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The new reseller was added but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "409": { + "description": "The given item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/reseller/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "Return the information about the reseller with the given id", + "operationId": "getReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the reseller to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Reseller with the id given in the system returned", + "schema": { + "$ref": "#/definitions/Reseller" + } + }, + "404": { + "description": "The reseller with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "Updates the information of the reseller with the given id", + "operationId": "updateReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the reseller to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Reseller to be updated", + "name": "reseller", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Reseller" + } + } + ], + "responses": { + "200": { + "description": "Reseller with the given id was updated", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The reseller was updated but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The reseller with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "customer", + "product", + "reseller" + ], + "type": "string", + "description": "Id of the product to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "Customer": { + "type": "object", + "properties": { + "AbacusCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "Address": { + "type": "string" + }, + "ApiLink": { + "type": "string", + "x-go-custom-tag": "gorm:\"-\"" + }, + "BillContact": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "BillCurrency": { + "description": "ISO-4217 currency code", + "type": "string", + "default": "CHF", + "enum": [ + "AED", + "AFN", + "ALL", + "AMD", + "ANG", + "AOA", + "ARS", + "AUD", + "AWG", + "AZN", + "BAM", + "BBD", + "BDT", + "BGN", + "BHD", + "BIF", + "BMD", + "BND", + "BOB", + "BOV", + "BRL", + "BSD", + "BTN", + "BWP", + "BYN", + "BZD", + "CAD", + "CDF", + "CHE", + "CHF", + "CHW", + "CLF", + "CLP", + "CNY", + "COP", + "COU", + "CRC", + "CUC", + "CUP", + "CVE", + "CZK", + "DJF", + "DKK", + "DOP", + "DZD", + "EGP", + "ERN", + "ETB", + "EUR", + "FJD", + "FKP", + "GBP", + "GEL", + "GHS", + "GIP", + "GMD", + "GNF", + "GTQ", + "GYD", + "HKD", + "HNL", + "HRK", + "HTG", + "HUF", + "IDR", + "ILS", + "INR", + "IQD", + "IRR", + "ISK", + "JMD", + "JOD", + "JPY", + "KES", + "KGS", + "KHR", + "KMF", + "KPW", + "KRW", + "KWD", + "KYD", + "KZT", + "LAK", + "LBP", + "LKR", + "LRD", + "LSL", + "LYD", + "MAD", + "MDL", + "MGA", + "MKD", + "MMK", + "MNT", + "MOP", + "MRU", + "MUR", + "MVR", + "MWK", + "MXN", + "MXV", + "MYR", + "MZN", + "NAD", + "NGN", + "NIO", + "NOK", + "NPR", + "NZD", + "OMR", + "PAB", + "PEN", + "PGK", + "PHP", + "PKR", + "PLN", + "PYG", + "QAR", + "RON", + "RSD", + "RUB", + "RWF", + "SAR", + "SBD", + "SCR", + "SDG", + "SEK", + "SGD", + "SHP", + "SLL", + "SOS", + "SRD", + "SSP", + "STN", + "SVC", + "SYP", + "SZL", + "THB", + "TJS", + "TMT", + "TND", + "TOP", + "TRY", + "TTD", + "TWD", + "TZS", + "UAH", + "UGX", + "USD", + "USN", + "UYI", + "UYU", + "UYW", + "UZS", + "VES", + "VND", + "VUV", + "WST", + "XAF", + "XAG", + "XAU", + "XBA", + "XBB", + "XBC", + "XBD", + "XCD", + "XDR", + "XOF", + "XPD", + "XPF", + "XPT", + "XSU", + "XTS", + "XUA", + "XXX", + "YER", + "ZAR", + "ZMW", + "ZWL" + ], + "x-go-custom-tag": "gorm:\"default:CHF\"" + }, + "BillPeriod": { + "type": "string", + "default": "monthly", + "enum": [ + "daily", + "weekly", + "bi-weekly", + "monthly", + "bi-monthly", + "quarterly", + "semi-annually", + "annually" + ], + "x-go-custom-tag": "gorm:\"default:monthly\"" + }, + "Billable": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "BillingCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "CancelDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2100-12-31\"" + }, + "ContractEnd": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2030-12-31\"" + }, + "ContractStart": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2019-01-01\"" + }, + "CustomerId": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "DeletedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"", + "x-nullable": true + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EmailBcc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailCc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailTo": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "InvoiceMode": { + "type": "string", + "default": "email", + "enum": [ + "email", + "post" + ], + "x-go-custom-tag": "gorm:\"default:email\"" + }, + "IsActive": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "Language": { + "description": "ISO-369-1 alpha-2 language codes", + "type": "string", + "default": "DE", + "enum": [ + "AA", + "AB", + "AE", + "AF", + "AK", + "AM", + "AN", + "AR", + "AS", + "AV", + "AY", + "AZ", + "BA", + "BE", + "BG", + "BH", + "BI", + "BM", + "BN", + "BO", + "BR", + "BS", + "CA", + "CE", + "CH", + "CO", + "CR", + "CS", + "CU", + "CV", + "CY", + "DA", + "DE", + "DV", + "DZ", + "EE", + "EL", + "EN", + "EO", + "ES", + "ET", + "EU", + "FA", + "FF", + "FI", + "FJ", + "FO", + "FR", + "FY", + "GA", + "GD", + "GL", + "GN", + "GU", + "GV", + "HA", + "HE", + "HI", + "HO", + "HR", + "HT", + "HU", + "HY", + "HZ", + "IA", + "ID", + "IE", + "IG", + "II", + "IK", + "IO", + "IS", + "IT", + "IU", + "JA", + "JV", + "KA", + "KG", + "KI", + "KJ", + "KK", + "KL", + "KM", + "KN", + "KO", + "KR", + "KS", + "KU", + "KV", + "KW", + "KY", + "LA", + "LB", + "LG", + "LI", + "LN", + "LO", + "LT", + "LU", + "LV", + "MG", + "MH", + "MI", + "MK", + "ML", + "MN", + "MR", + "MS", + "MT", + "MY", + "NA", + "NB", + "ND", + "NE", + "NG", + "NL", + "NN", + "NO", + "NR", + "NV", + "NY", + "OC", + "OJ", + "OM", + "OR", + "OS", + "PA", + "PI", + "PL", + "PS", + "PT", + "QU", + "RM", + "RN", + "RO", + "RU", + "RW", + "SA", + "SC", + "SD", + "SE", + "SG", + "SI", + "SK", + "SL", + "SM", + "SN", + "SO", + "SQ", + "SR", + "SS", + "ST", + "SU", + "SV", + "SW", + "TA", + "TE", + "TG", + "TH", + "TI", + "TK", + "TL", + "TN", + "TO", + "TR", + "TS", + "TT", + "TW", + "TY", + "UG", + "UK", + "UR", + "UZ", + "VE", + "VI", + "VO", + "WA", + "WO", + "XH", + "YI", + "YO", + "ZA", + "ZH", + "ZU" + ], + "x-go-custom-tag": "gorm:\"default:DE\"" + }, + "Name": { + "type": "string" + }, + "ParentCustomerId": { + "type": "string" + }, + "PlanId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:'DEFAULT'\"" + }, + "Products": { + "type": "array", + "items": { + "$ref": "#/definitions/Product" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "ResellerId": { + "type": "string" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Product": { + "type": "object", + "properties": { + "ApiLink": { + "type": "string", + "x-go-custom-tag": "gorm:\"-\"" + }, + "CancelDate": { + "type": "string", + "format": "date", + "default": "2100-12-31", + "x-go-custom-tag": "gorm:\"type:date;default:2100-12-31\"" + }, + "CustomerId": { + "type": "string" + }, + "DeletedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"", + "x-nullable": true + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "Name": { + "type": "string" + }, + "PlanId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:'DEFAULT'\"" + }, + "ProductId": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Type": { + "type": "string" + } + } + }, + "Reseller": { + "type": "object", + "properties": { + "AbacusCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "Address": { + "type": "string" + }, + "ApiLink": { + "type": "string", + "x-go-custom-tag": "gorm:\"-\"" + }, + "BillContact": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "BillCurrency": { + "description": "ISO-4217 currency code", + "type": "string", + "default": "CHF", + "enum": [ + "AED", + "AFN", + "ALL", + "AMD", + "ANG", + "AOA", + "ARS", + "AUD", + "AWG", + "AZN", + "BAM", + "BBD", + "BDT", + "BGN", + "BHD", + "BIF", + "BMD", + "BND", + "BOB", + "BOV", + "BRL", + "BSD", + "BTN", + "BWP", + "BYN", + "BZD", + "CAD", + "CDF", + "CHE", + "CHF", + "CHW", + "CLF", + "CLP", + "CNY", + "COP", + "COU", + "CRC", + "CUC", + "CUP", + "CVE", + "CZK", + "DJF", + "DKK", + "DOP", + "DZD", + "EGP", + "ERN", + "ETB", + "EUR", + "FJD", + "FKP", + "GBP", + "GEL", + "GHS", + "GIP", + "GMD", + "GNF", + "GTQ", + "GYD", + "HKD", + "HNL", + "HRK", + "HTG", + "HUF", + "IDR", + "ILS", + "INR", + "IQD", + "IRR", + "ISK", + "JMD", + "JOD", + "JPY", + "KES", + "KGS", + "KHR", + "KMF", + "KPW", + "KRW", + "KWD", + "KYD", + "KZT", + "LAK", + "LBP", + "LKR", + "LRD", + "LSL", + "LYD", + "MAD", + "MDL", + "MGA", + "MKD", + "MMK", + "MNT", + "MOP", + "MRU", + "MUR", + "MVR", + "MWK", + "MXN", + "MXV", + "MYR", + "MZN", + "NAD", + "NGN", + "NIO", + "NOK", + "NPR", + "NZD", + "OMR", + "PAB", + "PEN", + "PGK", + "PHP", + "PKR", + "PLN", + "PYG", + "QAR", + "RON", + "RSD", + "RUB", + "RWF", + "SAR", + "SBD", + "SCR", + "SDG", + "SEK", + "SGD", + "SHP", + "SLL", + "SOS", + "SRD", + "SSP", + "STN", + "SVC", + "SYP", + "SZL", + "THB", + "TJS", + "TMT", + "TND", + "TOP", + "TRY", + "TTD", + "TWD", + "TZS", + "UAH", + "UGX", + "USD", + "USN", + "UYI", + "UYU", + "UYW", + "UZS", + "VES", + "VND", + "VUV", + "WST", + "XAF", + "XAG", + "XAU", + "XBA", + "XBB", + "XBC", + "XBD", + "XCD", + "XDR", + "XOF", + "XPD", + "XPF", + "XPT", + "XSU", + "XTS", + "XUA", + "XXX", + "YER", + "ZAR", + "ZMW", + "ZWL" + ], + "x-go-custom-tag": "gorm:\"default:CHF\"" + }, + "BillPeriod": { + "type": "string", + "default": "monthly", + "enum": [ + "daily", + "weekly", + "bi-weekly", + "monthly", + "bi-monthly", + "quarterly", + "semi-annually", + "annually" + ], + "x-go-custom-tag": "gorm:\"default:monthly\"" + }, + "Billable": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "BillingCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "CancelDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2100-12-31\"" + }, + "ContractEnd": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2030-12-31\"" + }, + "ContractStart": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2019-01-01\"" + }, + "Customers": { + "type": "array", + "items": { + "$ref": "#/definitions/Customer" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "DeletedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"", + "x-nullable": true + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EmailBcc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailCc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailTo": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "InvoiceMode": { + "type": "string", + "default": "email", + "enum": [ + "email", + "post" + ], + "x-go-custom-tag": "gorm:\"default:email\"" + }, + "IsActive": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "Language": { + "description": "ISO-369-1 alpha-2 language codes", + "type": "string", + "default": "DE", + "enum": [ + "AA", + "AB", + "AE", + "AF", + "AK", + "AM", + "AN", + "AR", + "AS", + "AV", + "AY", + "AZ", + "BA", + "BE", + "BG", + "BH", + "BI", + "BM", + "BN", + "BO", + "BR", + "BS", + "CA", + "CE", + "CH", + "CO", + "CR", + "CS", + "CU", + "CV", + "CY", + "DA", + "DE", + "DV", + "DZ", + "EE", + "EL", + "EN", + "EO", + "ES", + "ET", + "EU", + "FA", + "FF", + "FI", + "FJ", + "FO", + "FR", + "FY", + "GA", + "GD", + "GL", + "GN", + "GU", + "GV", + "HA", + "HE", + "HI", + "HO", + "HR", + "HT", + "HU", + "HY", + "HZ", + "IA", + "ID", + "IE", + "IG", + "II", + "IK", + "IO", + "IS", + "IT", + "IU", + "JA", + "JV", + "KA", + "KG", + "KI", + "KJ", + "KK", + "KL", + "KM", + "KN", + "KO", + "KR", + "KS", + "KU", + "KV", + "KW", + "KY", + "LA", + "LB", + "LG", + "LI", + "LN", + "LO", + "LT", + "LU", + "LV", + "MG", + "MH", + "MI", + "MK", + "ML", + "MN", + "MR", + "MS", + "MT", + "MY", + "NA", + "NB", + "ND", + "NE", + "NG", + "NL", + "NN", + "NO", + "NR", + "NV", + "NY", + "OC", + "OJ", + "OM", + "OR", + "OS", + "PA", + "PI", + "PL", + "PS", + "PT", + "QU", + "RM", + "RN", + "RO", + "RU", + "RW", + "SA", + "SC", + "SD", + "SE", + "SG", + "SI", + "SK", + "SL", + "SM", + "SN", + "SO", + "SQ", + "SR", + "SS", + "ST", + "SU", + "SV", + "SW", + "TA", + "TE", + "TG", + "TH", + "TI", + "TK", + "TL", + "TN", + "TO", + "TR", + "TS", + "TT", + "TW", + "TY", + "UG", + "UK", + "UR", + "UZ", + "VE", + "VI", + "VO", + "WA", + "WO", + "XH", + "YI", + "YO", + "ZA", + "ZH", + "ZU" + ], + "x-go-custom-tag": "gorm:\"default:DE\"" + }, + "Name": { + "type": "string" + }, + "ParentResellerId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "PlanId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:'DEFAULT'\"" + }, + "ResellerId": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the management of Resellers", + "name": "resellerManagement" + }, + { + "description": "Actions relating to the management of Customers", + "name": "customerManagement" + }, + { + "description": "Actions relating to the management of Products", + "name": "productManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of customers and products", + "title": "Customer Database Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/customer": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "List all the customers in the system", + "operationId": "listCustomers", + "responses": { + "200": { + "description": "List of customers in the system returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Customer" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "Insert a new customer in the system.", + "operationId": "addCustomer", + "parameters": [ + { + "description": "Customer to be added", + "name": "customer", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Customer" + } + } + ], + "responses": { + "201": { + "description": "New customer was added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The new customer was added but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "409": { + "description": "The given item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/customer/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "Return the information about the customer with the given id", + "operationId": "getCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the customer to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Customer with the id given in the system returned", + "schema": { + "$ref": "#/definitions/Customer" + } + }, + "404": { + "description": "The customer with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "customerManagement" + ], + "summary": "Updates the information of the customer with the given id", + "operationId": "updateCustomer", + "parameters": [ + { + "type": "string", + "description": "Id of the customer to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Customer to be updated", + "name": "customer", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Customer" + } + } + ], + "responses": { + "200": { + "description": "Customer with the given id was updated", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The customer was updated but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The customer with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/product": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "List all the products in the system", + "operationId": "listProducts", + "responses": { + "200": { + "description": "List of products in the system returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Product" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "Insert a new product in the system.", + "operationId": "addProduct", + "parameters": [ + { + "description": "Product to be added", + "name": "product", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Product" + } + } + ], + "responses": { + "201": { + "description": "New product was added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "409": { + "description": "The given item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/product/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "Return the information about the product with the given id", + "operationId": "getProduct", + "parameters": [ + { + "type": "string", + "description": "Id of the product to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Product with the id given in the system returned", + "schema": { + "$ref": "#/definitions/Product" + } + }, + "404": { + "description": "The product with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "productManagement" + ], + "summary": "Updates the information of the product with the given id", + "operationId": "updateProduct", + "parameters": [ + { + "type": "string", + "description": "Id of the product to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Product to be updated", + "name": "product", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Product" + } + } + ], + "responses": { + "200": { + "description": "Product with the given id was updated", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The product with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/reseller": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "List all the resellers in the system", + "operationId": "listResellers", + "responses": { + "200": { + "description": "List of resellers in the system returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Reseller" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "Insert a new reseller in the system.", + "operationId": "addReseller", + "parameters": [ + { + "description": "Reseller to be added", + "name": "reseller", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Reseller" + } + } + ], + "responses": { + "201": { + "description": "New reseller was added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The new reseller was added but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "409": { + "description": "The given item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/reseller/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "Return the information about the reseller with the given id", + "operationId": "getReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the reseller to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Reseller with the id given in the system returned", + "schema": { + "$ref": "#/definitions/Reseller" + } + }, + "404": { + "description": "The reseller with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "resellerManagement" + ], + "summary": "Updates the information of the reseller with the given id", + "operationId": "updateReseller", + "parameters": [ + { + "type": "string", + "description": "Id of the reseller to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "Reseller to be updated", + "name": "reseller", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Reseller" + } + } + ], + "responses": { + "200": { + "description": "Reseller with the given id was updated", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "202": { + "description": "The reseller was updated but there might have been some fails when adding part of the data", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "404": { + "description": "The reseller with the given id wasn't found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "customer", + "product", + "reseller" + ], + "type": "string", + "description": "Id of the product to be retrieved", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "Customer": { + "type": "object", + "properties": { + "AbacusCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "Address": { + "type": "string" + }, + "ApiLink": { + "type": "string", + "x-go-custom-tag": "gorm:\"-\"" + }, + "BillContact": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "BillCurrency": { + "description": "ISO-4217 currency code", + "type": "string", + "default": "CHF", + "enum": [ + "AED", + "AFN", + "ALL", + "AMD", + "ANG", + "AOA", + "ARS", + "AUD", + "AWG", + "AZN", + "BAM", + "BBD", + "BDT", + "BGN", + "BHD", + "BIF", + "BMD", + "BND", + "BOB", + "BOV", + "BRL", + "BSD", + "BTN", + "BWP", + "BYN", + "BZD", + "CAD", + "CDF", + "CHE", + "CHF", + "CHW", + "CLF", + "CLP", + "CNY", + "COP", + "COU", + "CRC", + "CUC", + "CUP", + "CVE", + "CZK", + "DJF", + "DKK", + "DOP", + "DZD", + "EGP", + "ERN", + "ETB", + "EUR", + "FJD", + "FKP", + "GBP", + "GEL", + "GHS", + "GIP", + "GMD", + "GNF", + "GTQ", + "GYD", + "HKD", + "HNL", + "HRK", + "HTG", + "HUF", + "IDR", + "ILS", + "INR", + "IQD", + "IRR", + "ISK", + "JMD", + "JOD", + "JPY", + "KES", + "KGS", + "KHR", + "KMF", + "KPW", + "KRW", + "KWD", + "KYD", + "KZT", + "LAK", + "LBP", + "LKR", + "LRD", + "LSL", + "LYD", + "MAD", + "MDL", + "MGA", + "MKD", + "MMK", + "MNT", + "MOP", + "MRU", + "MUR", + "MVR", + "MWK", + "MXN", + "MXV", + "MYR", + "MZN", + "NAD", + "NGN", + "NIO", + "NOK", + "NPR", + "NZD", + "OMR", + "PAB", + "PEN", + "PGK", + "PHP", + "PKR", + "PLN", + "PYG", + "QAR", + "RON", + "RSD", + "RUB", + "RWF", + "SAR", + "SBD", + "SCR", + "SDG", + "SEK", + "SGD", + "SHP", + "SLL", + "SOS", + "SRD", + "SSP", + "STN", + "SVC", + "SYP", + "SZL", + "THB", + "TJS", + "TMT", + "TND", + "TOP", + "TRY", + "TTD", + "TWD", + "TZS", + "UAH", + "UGX", + "USD", + "USN", + "UYI", + "UYU", + "UYW", + "UZS", + "VES", + "VND", + "VUV", + "WST", + "XAF", + "XAG", + "XAU", + "XBA", + "XBB", + "XBC", + "XBD", + "XCD", + "XDR", + "XOF", + "XPD", + "XPF", + "XPT", + "XSU", + "XTS", + "XUA", + "XXX", + "YER", + "ZAR", + "ZMW", + "ZWL" + ], + "x-go-custom-tag": "gorm:\"default:CHF\"" + }, + "BillPeriod": { + "type": "string", + "default": "monthly", + "enum": [ + "daily", + "weekly", + "bi-weekly", + "monthly", + "bi-monthly", + "quarterly", + "semi-annually", + "annually" + ], + "x-go-custom-tag": "gorm:\"default:monthly\"" + }, + "Billable": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "BillingCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "CancelDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2100-12-31\"" + }, + "ContractEnd": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2030-12-31\"" + }, + "ContractStart": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2019-01-01\"" + }, + "CustomerId": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "DeletedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"", + "x-nullable": true + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EmailBcc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailCc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailTo": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "InvoiceMode": { + "type": "string", + "default": "email", + "enum": [ + "email", + "post" + ], + "x-go-custom-tag": "gorm:\"default:email\"" + }, + "IsActive": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "Language": { + "description": "ISO-369-1 alpha-2 language codes", + "type": "string", + "default": "DE", + "enum": [ + "AA", + "AB", + "AE", + "AF", + "AK", + "AM", + "AN", + "AR", + "AS", + "AV", + "AY", + "AZ", + "BA", + "BE", + "BG", + "BH", + "BI", + "BM", + "BN", + "BO", + "BR", + "BS", + "CA", + "CE", + "CH", + "CO", + "CR", + "CS", + "CU", + "CV", + "CY", + "DA", + "DE", + "DV", + "DZ", + "EE", + "EL", + "EN", + "EO", + "ES", + "ET", + "EU", + "FA", + "FF", + "FI", + "FJ", + "FO", + "FR", + "FY", + "GA", + "GD", + "GL", + "GN", + "GU", + "GV", + "HA", + "HE", + "HI", + "HO", + "HR", + "HT", + "HU", + "HY", + "HZ", + "IA", + "ID", + "IE", + "IG", + "II", + "IK", + "IO", + "IS", + "IT", + "IU", + "JA", + "JV", + "KA", + "KG", + "KI", + "KJ", + "KK", + "KL", + "KM", + "KN", + "KO", + "KR", + "KS", + "KU", + "KV", + "KW", + "KY", + "LA", + "LB", + "LG", + "LI", + "LN", + "LO", + "LT", + "LU", + "LV", + "MG", + "MH", + "MI", + "MK", + "ML", + "MN", + "MR", + "MS", + "MT", + "MY", + "NA", + "NB", + "ND", + "NE", + "NG", + "NL", + "NN", + "NO", + "NR", + "NV", + "NY", + "OC", + "OJ", + "OM", + "OR", + "OS", + "PA", + "PI", + "PL", + "PS", + "PT", + "QU", + "RM", + "RN", + "RO", + "RU", + "RW", + "SA", + "SC", + "SD", + "SE", + "SG", + "SI", + "SK", + "SL", + "SM", + "SN", + "SO", + "SQ", + "SR", + "SS", + "ST", + "SU", + "SV", + "SW", + "TA", + "TE", + "TG", + "TH", + "TI", + "TK", + "TL", + "TN", + "TO", + "TR", + "TS", + "TT", + "TW", + "TY", + "UG", + "UK", + "UR", + "UZ", + "VE", + "VI", + "VO", + "WA", + "WO", + "XH", + "YI", + "YO", + "ZA", + "ZH", + "ZU" + ], + "x-go-custom-tag": "gorm:\"default:DE\"" + }, + "Name": { + "type": "string" + }, + "ParentCustomerId": { + "type": "string" + }, + "PlanId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:'DEFAULT'\"" + }, + "Products": { + "type": "array", + "items": { + "$ref": "#/definitions/Product" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "ResellerId": { + "type": "string" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Product": { + "type": "object", + "properties": { + "ApiLink": { + "type": "string", + "x-go-custom-tag": "gorm:\"-\"" + }, + "CancelDate": { + "type": "string", + "format": "date", + "default": "2100-12-31", + "x-go-custom-tag": "gorm:\"type:date;default:2100-12-31\"" + }, + "CustomerId": { + "type": "string" + }, + "DeletedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"", + "x-nullable": true + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "Name": { + "type": "string" + }, + "PlanId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:'DEFAULT'\"" + }, + "ProductId": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Type": { + "type": "string" + } + } + }, + "Reseller": { + "type": "object", + "properties": { + "AbacusCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "Address": { + "type": "string" + }, + "ApiLink": { + "type": "string", + "x-go-custom-tag": "gorm:\"-\"" + }, + "BillContact": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "BillCurrency": { + "description": "ISO-4217 currency code", + "type": "string", + "default": "CHF", + "enum": [ + "AED", + "AFN", + "ALL", + "AMD", + "ANG", + "AOA", + "ARS", + "AUD", + "AWG", + "AZN", + "BAM", + "BBD", + "BDT", + "BGN", + "BHD", + "BIF", + "BMD", + "BND", + "BOB", + "BOV", + "BRL", + "BSD", + "BTN", + "BWP", + "BYN", + "BZD", + "CAD", + "CDF", + "CHE", + "CHF", + "CHW", + "CLF", + "CLP", + "CNY", + "COP", + "COU", + "CRC", + "CUC", + "CUP", + "CVE", + "CZK", + "DJF", + "DKK", + "DOP", + "DZD", + "EGP", + "ERN", + "ETB", + "EUR", + "FJD", + "FKP", + "GBP", + "GEL", + "GHS", + "GIP", + "GMD", + "GNF", + "GTQ", + "GYD", + "HKD", + "HNL", + "HRK", + "HTG", + "HUF", + "IDR", + "ILS", + "INR", + "IQD", + "IRR", + "ISK", + "JMD", + "JOD", + "JPY", + "KES", + "KGS", + "KHR", + "KMF", + "KPW", + "KRW", + "KWD", + "KYD", + "KZT", + "LAK", + "LBP", + "LKR", + "LRD", + "LSL", + "LYD", + "MAD", + "MDL", + "MGA", + "MKD", + "MMK", + "MNT", + "MOP", + "MRU", + "MUR", + "MVR", + "MWK", + "MXN", + "MXV", + "MYR", + "MZN", + "NAD", + "NGN", + "NIO", + "NOK", + "NPR", + "NZD", + "OMR", + "PAB", + "PEN", + "PGK", + "PHP", + "PKR", + "PLN", + "PYG", + "QAR", + "RON", + "RSD", + "RUB", + "RWF", + "SAR", + "SBD", + "SCR", + "SDG", + "SEK", + "SGD", + "SHP", + "SLL", + "SOS", + "SRD", + "SSP", + "STN", + "SVC", + "SYP", + "SZL", + "THB", + "TJS", + "TMT", + "TND", + "TOP", + "TRY", + "TTD", + "TWD", + "TZS", + "UAH", + "UGX", + "USD", + "USN", + "UYI", + "UYU", + "UYW", + "UZS", + "VES", + "VND", + "VUV", + "WST", + "XAF", + "XAG", + "XAU", + "XBA", + "XBB", + "XBC", + "XBD", + "XCD", + "XDR", + "XOF", + "XPD", + "XPF", + "XPT", + "XSU", + "XTS", + "XUA", + "XXX", + "YER", + "ZAR", + "ZMW", + "ZWL" + ], + "x-go-custom-tag": "gorm:\"default:CHF\"" + }, + "BillPeriod": { + "type": "string", + "default": "monthly", + "enum": [ + "daily", + "weekly", + "bi-weekly", + "monthly", + "bi-monthly", + "quarterly", + "semi-annually", + "annually" + ], + "x-go-custom-tag": "gorm:\"default:monthly\"" + }, + "Billable": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "BillingCode": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "CancelDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2100-12-31\"" + }, + "ContractEnd": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2030-12-31\"" + }, + "ContractStart": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date;default:2019-01-01\"" + }, + "Customers": { + "type": "array", + "items": { + "$ref": "#/definitions/Customer" + }, + "x-go-custom-tag": "gorm:\"-\"" + }, + "DeletedAt": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"type:timestamptz\"", + "x-nullable": true + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "EmailBcc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailCc": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "EmailTo": { + "type": "string", + "format": "email", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "InvoiceMode": { + "type": "string", + "default": "email", + "enum": [ + "email", + "post" + ], + "x-go-custom-tag": "gorm:\"default:email\"" + }, + "IsActive": { + "type": "boolean", + "default": true, + "x-go-custom-tag": "gorm:\"default:true\"" + }, + "Language": { + "description": "ISO-369-1 alpha-2 language codes", + "type": "string", + "default": "DE", + "enum": [ + "AA", + "AB", + "AE", + "AF", + "AK", + "AM", + "AN", + "AR", + "AS", + "AV", + "AY", + "AZ", + "BA", + "BE", + "BG", + "BH", + "BI", + "BM", + "BN", + "BO", + "BR", + "BS", + "CA", + "CE", + "CH", + "CO", + "CR", + "CS", + "CU", + "CV", + "CY", + "DA", + "DE", + "DV", + "DZ", + "EE", + "EL", + "EN", + "EO", + "ES", + "ET", + "EU", + "FA", + "FF", + "FI", + "FJ", + "FO", + "FR", + "FY", + "GA", + "GD", + "GL", + "GN", + "GU", + "GV", + "HA", + "HE", + "HI", + "HO", + "HR", + "HT", + "HU", + "HY", + "HZ", + "IA", + "ID", + "IE", + "IG", + "II", + "IK", + "IO", + "IS", + "IT", + "IU", + "JA", + "JV", + "KA", + "KG", + "KI", + "KJ", + "KK", + "KL", + "KM", + "KN", + "KO", + "KR", + "KS", + "KU", + "KV", + "KW", + "KY", + "LA", + "LB", + "LG", + "LI", + "LN", + "LO", + "LT", + "LU", + "LV", + "MG", + "MH", + "MI", + "MK", + "ML", + "MN", + "MR", + "MS", + "MT", + "MY", + "NA", + "NB", + "ND", + "NE", + "NG", + "NL", + "NN", + "NO", + "NR", + "NV", + "NY", + "OC", + "OJ", + "OM", + "OR", + "OS", + "PA", + "PI", + "PL", + "PS", + "PT", + "QU", + "RM", + "RN", + "RO", + "RU", + "RW", + "SA", + "SC", + "SD", + "SE", + "SG", + "SI", + "SK", + "SL", + "SM", + "SN", + "SO", + "SQ", + "SR", + "SS", + "ST", + "SU", + "SV", + "SW", + "TA", + "TE", + "TG", + "TH", + "TI", + "TK", + "TL", + "TN", + "TO", + "TR", + "TS", + "TT", + "TW", + "TY", + "UG", + "UK", + "UR", + "UZ", + "VE", + "VI", + "VO", + "WA", + "WO", + "XH", + "YI", + "YO", + "ZA", + "ZH", + "ZU" + ], + "x-go-custom-tag": "gorm:\"default:DE\"" + }, + "Name": { + "type": "string" + }, + "ParentResellerId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:''\"" + }, + "PlanId": { + "type": "string", + "x-go-custom-tag": "gorm:\"default:'DEFAULT'\"" + }, + "ResellerId": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the management of Resellers", + "name": "resellerManagement" + }, + { + "description": "Actions relating to the management of Customers", + "name": "customerManagement" + }, + { + "description": "Actions relating to the management of Products", + "name": "productManagement" + } + ] +}`)) +} diff --git a/services/customerdb/restapi/operations/customer_database_management_api.go b/services/customerdb/restapi/operations/customer_database_management_api.go new file mode 100644 index 0000000..acb41a1 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_database_management_api.go @@ -0,0 +1,512 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/customer_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/product_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/reseller_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/trigger_management" +) + +// NewCustomerDatabaseManagementAPI creates a new CustomerDatabaseManagement instance +func NewCustomerDatabaseManagementAPI(spec *loads.Document) *CustomerDatabaseManagementAPI { + return &CustomerDatabaseManagementAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + CustomerManagementAddCustomerHandler: customer_management.AddCustomerHandlerFunc(func(params customer_management.AddCustomerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation customer_management.AddCustomer has not yet been implemented") + }), + ProductManagementAddProductHandler: product_management.AddProductHandlerFunc(func(params product_management.AddProductParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation product_management.AddProduct has not yet been implemented") + }), + ResellerManagementAddResellerHandler: reseller_management.AddResellerHandlerFunc(func(params reseller_management.AddResellerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation reseller_management.AddReseller has not yet been implemented") + }), + TriggerManagementExecSampleHandler: trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.ExecSample has not yet been implemented") + }), + CustomerManagementGetCustomerHandler: customer_management.GetCustomerHandlerFunc(func(params customer_management.GetCustomerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation customer_management.GetCustomer has not yet been implemented") + }), + ProductManagementGetProductHandler: product_management.GetProductHandlerFunc(func(params product_management.GetProductParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation product_management.GetProduct has not yet been implemented") + }), + ResellerManagementGetResellerHandler: reseller_management.GetResellerHandlerFunc(func(params reseller_management.GetResellerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation reseller_management.GetReseller has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + CustomerManagementListCustomersHandler: customer_management.ListCustomersHandlerFunc(func(params customer_management.ListCustomersParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation customer_management.ListCustomers has not yet been implemented") + }), + ProductManagementListProductsHandler: product_management.ListProductsHandlerFunc(func(params product_management.ListProductsParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation product_management.ListProducts has not yet been implemented") + }), + ResellerManagementListResellersHandler: reseller_management.ListResellersHandlerFunc(func(params reseller_management.ListResellersParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation reseller_management.ListResellers has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + CustomerManagementUpdateCustomerHandler: customer_management.UpdateCustomerHandlerFunc(func(params customer_management.UpdateCustomerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation customer_management.UpdateCustomer has not yet been implemented") + }), + ProductManagementUpdateProductHandler: product_management.UpdateProductHandlerFunc(func(params product_management.UpdateProductParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation product_management.UpdateProduct has not yet been implemented") + }), + ResellerManagementUpdateResellerHandler: reseller_management.UpdateResellerHandlerFunc(func(params reseller_management.UpdateResellerParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation reseller_management.UpdateReseller has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*CustomerDatabaseManagementAPI An API which supports creation, deletion, listing etc of customers and products */ +type CustomerDatabaseManagementAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // CustomerManagementAddCustomerHandler sets the operation handler for the add customer operation + CustomerManagementAddCustomerHandler customer_management.AddCustomerHandler + // ProductManagementAddProductHandler sets the operation handler for the add product operation + ProductManagementAddProductHandler product_management.AddProductHandler + // ResellerManagementAddResellerHandler sets the operation handler for the add reseller operation + ResellerManagementAddResellerHandler reseller_management.AddResellerHandler + // TriggerManagementExecSampleHandler sets the operation handler for the exec sample operation + TriggerManagementExecSampleHandler trigger_management.ExecSampleHandler + // CustomerManagementGetCustomerHandler sets the operation handler for the get customer operation + CustomerManagementGetCustomerHandler customer_management.GetCustomerHandler + // ProductManagementGetProductHandler sets the operation handler for the get product operation + ProductManagementGetProductHandler product_management.GetProductHandler + // ResellerManagementGetResellerHandler sets the operation handler for the get reseller operation + ResellerManagementGetResellerHandler reseller_management.GetResellerHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // CustomerManagementListCustomersHandler sets the operation handler for the list customers operation + CustomerManagementListCustomersHandler customer_management.ListCustomersHandler + // ProductManagementListProductsHandler sets the operation handler for the list products operation + ProductManagementListProductsHandler product_management.ListProductsHandler + // ResellerManagementListResellersHandler sets the operation handler for the list resellers operation + ResellerManagementListResellersHandler reseller_management.ListResellersHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // CustomerManagementUpdateCustomerHandler sets the operation handler for the update customer operation + CustomerManagementUpdateCustomerHandler customer_management.UpdateCustomerHandler + // ProductManagementUpdateProductHandler sets the operation handler for the update product operation + ProductManagementUpdateProductHandler product_management.UpdateProductHandler + // ResellerManagementUpdateResellerHandler sets the operation handler for the update reseller operation + ResellerManagementUpdateResellerHandler reseller_management.UpdateResellerHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// SetDefaultProduces sets the default produces media type +func (o *CustomerDatabaseManagementAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *CustomerDatabaseManagementAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *CustomerDatabaseManagementAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *CustomerDatabaseManagementAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *CustomerDatabaseManagementAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *CustomerDatabaseManagementAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *CustomerDatabaseManagementAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the CustomerDatabaseManagementAPI +func (o *CustomerDatabaseManagementAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.CustomerManagementAddCustomerHandler == nil { + unregistered = append(unregistered, "customer_management.AddCustomerHandler") + } + if o.ProductManagementAddProductHandler == nil { + unregistered = append(unregistered, "product_management.AddProductHandler") + } + if o.ResellerManagementAddResellerHandler == nil { + unregistered = append(unregistered, "reseller_management.AddResellerHandler") + } + if o.TriggerManagementExecSampleHandler == nil { + unregistered = append(unregistered, "trigger_management.ExecSampleHandler") + } + if o.CustomerManagementGetCustomerHandler == nil { + unregistered = append(unregistered, "customer_management.GetCustomerHandler") + } + if o.ProductManagementGetProductHandler == nil { + unregistered = append(unregistered, "product_management.GetProductHandler") + } + if o.ResellerManagementGetResellerHandler == nil { + unregistered = append(unregistered, "reseller_management.GetResellerHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.CustomerManagementListCustomersHandler == nil { + unregistered = append(unregistered, "customer_management.ListCustomersHandler") + } + if o.ProductManagementListProductsHandler == nil { + unregistered = append(unregistered, "product_management.ListProductsHandler") + } + if o.ResellerManagementListResellersHandler == nil { + unregistered = append(unregistered, "reseller_management.ListResellersHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + if o.CustomerManagementUpdateCustomerHandler == nil { + unregistered = append(unregistered, "customer_management.UpdateCustomerHandler") + } + if o.ProductManagementUpdateProductHandler == nil { + unregistered = append(unregistered, "product_management.UpdateProductHandler") + } + if o.ResellerManagementUpdateResellerHandler == nil { + unregistered = append(unregistered, "reseller_management.UpdateResellerHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *CustomerDatabaseManagementAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *CustomerDatabaseManagementAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *CustomerDatabaseManagementAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *CustomerDatabaseManagementAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *CustomerDatabaseManagementAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *CustomerDatabaseManagementAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the customer database management API +func (o *CustomerDatabaseManagementAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *CustomerDatabaseManagementAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/customer"] = customer_management.NewAddCustomer(o.context, o.CustomerManagementAddCustomerHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/product"] = product_management.NewAddProduct(o.context, o.ProductManagementAddProductHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/reseller"] = reseller_management.NewAddReseller(o.context, o.ResellerManagementAddResellerHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/sample"] = trigger_management.NewExecSample(o.context, o.TriggerManagementExecSampleHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/customer/{id}"] = customer_management.NewGetCustomer(o.context, o.CustomerManagementGetCustomerHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/product/{id}"] = product_management.NewGetProduct(o.context, o.ProductManagementGetProductHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/reseller/{id}"] = reseller_management.NewGetReseller(o.context, o.ResellerManagementGetResellerHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/customer"] = customer_management.NewListCustomers(o.context, o.CustomerManagementListCustomersHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/product"] = product_management.NewListProducts(o.context, o.ProductManagementListProductsHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/reseller"] = reseller_management.NewListResellers(o.context, o.ResellerManagementListResellersHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/customer/{id}"] = customer_management.NewUpdateCustomer(o.context, o.CustomerManagementUpdateCustomerHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/product/{id}"] = product_management.NewUpdateProduct(o.context, o.ProductManagementUpdateProductHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/reseller/{id}"] = reseller_management.NewUpdateReseller(o.context, o.ResellerManagementUpdateResellerHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *CustomerDatabaseManagementAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *CustomerDatabaseManagementAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *CustomerDatabaseManagementAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *CustomerDatabaseManagementAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *CustomerDatabaseManagementAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/services/customerdb/restapi/operations/customer_management/add_customer.go b/services/customerdb/restapi/operations/customer_management/add_customer.go new file mode 100644 index 0000000..6cdb8ac --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/add_customer.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// AddCustomerHandlerFunc turns a function with the right signature into a add customer handler +type AddCustomerHandlerFunc func(AddCustomerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn AddCustomerHandlerFunc) Handle(params AddCustomerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// AddCustomerHandler interface for that can handle valid add customer params +type AddCustomerHandler interface { + Handle(AddCustomerParams, interface{}) middleware.Responder +} + +// NewAddCustomer creates a new http.Handler for the add customer operation +func NewAddCustomer(ctx *middleware.Context, handler AddCustomerHandler) *AddCustomer { + return &AddCustomer{Context: ctx, Handler: handler} +} + +/*AddCustomer swagger:route POST /customer customerManagement addCustomer + +Insert a new customer in the system. + +*/ +type AddCustomer struct { + Context *middleware.Context + Handler AddCustomerHandler +} + +func (o *AddCustomer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewAddCustomerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/customer_management/add_customer_parameters.go b/services/customerdb/restapi/operations/customer_management/add_customer_parameters.go new file mode 100644 index 0000000..1a9284c --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/add_customer_parameters.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewAddCustomerParams creates a new AddCustomerParams object +// no default values defined in spec. +func NewAddCustomerParams() AddCustomerParams { + + return AddCustomerParams{} +} + +// AddCustomerParams contains all the bound params for the add customer operation +// typically these are obtained from a http.Request +// +// swagger:parameters addCustomer +type AddCustomerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Customer to be added + Required: true + In: body + */ + Customer *models.Customer +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewAddCustomerParams() beforehand. +func (o *AddCustomerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Customer + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("customer", "body", "")) + } else { + res = append(res, errors.NewParseError("customer", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Customer = &body + } + } + } else { + res = append(res, errors.Required("customer", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/customer_management/add_customer_responses.go b/services/customerdb/restapi/operations/customer_management/add_customer_responses.go new file mode 100644 index 0000000..39c2489 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/add_customer_responses.go @@ -0,0 +1,214 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// AddCustomerCreatedCode is the HTTP code returned for type AddCustomerCreated +const AddCustomerCreatedCode int = 201 + +/*AddCustomerCreated New customer was added successfully + +swagger:response addCustomerCreated +*/ +type AddCustomerCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewAddCustomerCreated creates AddCustomerCreated with default headers values +func NewAddCustomerCreated() *AddCustomerCreated { + + return &AddCustomerCreated{} +} + +// WithPayload adds the payload to the add customer created response +func (o *AddCustomerCreated) WithPayload(payload *models.ItemCreatedResponse) *AddCustomerCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add customer created response +func (o *AddCustomerCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddCustomerCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddCustomerAcceptedCode is the HTTP code returned for type AddCustomerAccepted +const AddCustomerAcceptedCode int = 202 + +/*AddCustomerAccepted The new customer was added but there might have been some fails when adding part of the data + +swagger:response addCustomerAccepted +*/ +type AddCustomerAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewAddCustomerAccepted creates AddCustomerAccepted with default headers values +func NewAddCustomerAccepted() *AddCustomerAccepted { + + return &AddCustomerAccepted{} +} + +// WithPayload adds the payload to the add customer accepted response +func (o *AddCustomerAccepted) WithPayload(payload *models.ItemCreatedResponse) *AddCustomerAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add customer accepted response +func (o *AddCustomerAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddCustomerAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddCustomerBadRequestCode is the HTTP code returned for type AddCustomerBadRequest +const AddCustomerBadRequestCode int = 400 + +/*AddCustomerBadRequest Invalid input, object invalid + +swagger:response addCustomerBadRequest +*/ +type AddCustomerBadRequest struct { +} + +// NewAddCustomerBadRequest creates AddCustomerBadRequest with default headers values +func NewAddCustomerBadRequest() *AddCustomerBadRequest { + + return &AddCustomerBadRequest{} +} + +// WriteResponse to the client +func (o *AddCustomerBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// AddCustomerConflictCode is the HTTP code returned for type AddCustomerConflict +const AddCustomerConflictCode int = 409 + +/*AddCustomerConflict The given item already exists + +swagger:response addCustomerConflict +*/ +type AddCustomerConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddCustomerConflict creates AddCustomerConflict with default headers values +func NewAddCustomerConflict() *AddCustomerConflict { + + return &AddCustomerConflict{} +} + +// WithPayload adds the payload to the add customer conflict response +func (o *AddCustomerConflict) WithPayload(payload *models.ErrorResponse) *AddCustomerConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add customer conflict response +func (o *AddCustomerConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddCustomerConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddCustomerInternalServerErrorCode is the HTTP code returned for type AddCustomerInternalServerError +const AddCustomerInternalServerErrorCode int = 500 + +/*AddCustomerInternalServerError Something unexpected happend, error raised + +swagger:response addCustomerInternalServerError +*/ +type AddCustomerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddCustomerInternalServerError creates AddCustomerInternalServerError with default headers values +func NewAddCustomerInternalServerError() *AddCustomerInternalServerError { + + return &AddCustomerInternalServerError{} +} + +// WithPayload adds the payload to the add customer internal server error response +func (o *AddCustomerInternalServerError) WithPayload(payload *models.ErrorResponse) *AddCustomerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add customer internal server error response +func (o *AddCustomerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddCustomerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/customer_management/add_customer_urlbuilder.go b/services/customerdb/restapi/operations/customer_management/add_customer_urlbuilder.go new file mode 100644 index 0000000..116b91e --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/add_customer_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// AddCustomerURL generates an URL for the add customer operation +type AddCustomerURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddCustomerURL) WithBasePath(bp string) *AddCustomerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddCustomerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *AddCustomerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/customer" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *AddCustomerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *AddCustomerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *AddCustomerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on AddCustomerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on AddCustomerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *AddCustomerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/customer_management/get_customer.go b/services/customerdb/restapi/operations/customer_management/get_customer.go new file mode 100644 index 0000000..ba379a5 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/get_customer.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetCustomerHandlerFunc turns a function with the right signature into a get customer handler +type GetCustomerHandlerFunc func(GetCustomerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetCustomerHandlerFunc) Handle(params GetCustomerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetCustomerHandler interface for that can handle valid get customer params +type GetCustomerHandler interface { + Handle(GetCustomerParams, interface{}) middleware.Responder +} + +// NewGetCustomer creates a new http.Handler for the get customer operation +func NewGetCustomer(ctx *middleware.Context, handler GetCustomerHandler) *GetCustomer { + return &GetCustomer{Context: ctx, Handler: handler} +} + +/*GetCustomer swagger:route GET /customer/{id} customerManagement getCustomer + +Return the information about the customer with the given id + +*/ +type GetCustomer struct { + Context *middleware.Context + Handler GetCustomerHandler +} + +func (o *GetCustomer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetCustomerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/customer_management/get_customer_parameters.go b/services/customerdb/restapi/operations/customer_management/get_customer_parameters.go new file mode 100644 index 0000000..2ff8adc --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/get_customer_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetCustomerParams creates a new GetCustomerParams object +// no default values defined in spec. +func NewGetCustomerParams() GetCustomerParams { + + return GetCustomerParams{} +} + +// GetCustomerParams contains all the bound params for the get customer operation +// typically these are obtained from a http.Request +// +// swagger:parameters getCustomer +type GetCustomerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the customer to be retrieved + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetCustomerParams() beforehand. +func (o *GetCustomerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetCustomerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/customerdb/restapi/operations/customer_management/get_customer_responses.go b/services/customerdb/restapi/operations/customer_management/get_customer_responses.go new file mode 100644 index 0000000..f9e1358 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/get_customer_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetCustomerOKCode is the HTTP code returned for type GetCustomerOK +const GetCustomerOKCode int = 200 + +/*GetCustomerOK Customer with the id given in the system returned + +swagger:response getCustomerOK +*/ +type GetCustomerOK struct { + + /* + In: Body + */ + Payload *models.Customer `json:"body,omitempty"` +} + +// NewGetCustomerOK creates GetCustomerOK with default headers values +func NewGetCustomerOK() *GetCustomerOK { + + return &GetCustomerOK{} +} + +// WithPayload adds the payload to the get customer o k response +func (o *GetCustomerOK) WithPayload(payload *models.Customer) *GetCustomerOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get customer o k response +func (o *GetCustomerOK) SetPayload(payload *models.Customer) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCustomerOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCustomerNotFoundCode is the HTTP code returned for type GetCustomerNotFound +const GetCustomerNotFoundCode int = 404 + +/*GetCustomerNotFound The customer with the given id wasn't found + +swagger:response getCustomerNotFound +*/ +type GetCustomerNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCustomerNotFound creates GetCustomerNotFound with default headers values +func NewGetCustomerNotFound() *GetCustomerNotFound { + + return &GetCustomerNotFound{} +} + +// WithPayload adds the payload to the get customer not found response +func (o *GetCustomerNotFound) WithPayload(payload *models.ErrorResponse) *GetCustomerNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get customer not found response +func (o *GetCustomerNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCustomerNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCustomerInternalServerErrorCode is the HTTP code returned for type GetCustomerInternalServerError +const GetCustomerInternalServerErrorCode int = 500 + +/*GetCustomerInternalServerError Something unexpected happend, error raised + +swagger:response getCustomerInternalServerError +*/ +type GetCustomerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCustomerInternalServerError creates GetCustomerInternalServerError with default headers values +func NewGetCustomerInternalServerError() *GetCustomerInternalServerError { + + return &GetCustomerInternalServerError{} +} + +// WithPayload adds the payload to the get customer internal server error response +func (o *GetCustomerInternalServerError) WithPayload(payload *models.ErrorResponse) *GetCustomerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get customer internal server error response +func (o *GetCustomerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCustomerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/customer_management/get_customer_urlbuilder.go b/services/customerdb/restapi/operations/customer_management/get_customer_urlbuilder.go new file mode 100644 index 0000000..1f3d410 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/get_customer_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetCustomerURL generates an URL for the get customer operation +type GetCustomerURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCustomerURL) WithBasePath(bp string) *GetCustomerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCustomerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetCustomerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/customer/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetCustomerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetCustomerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetCustomerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetCustomerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetCustomerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetCustomerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetCustomerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/customer_management/list_customers.go b/services/customerdb/restapi/operations/customer_management/list_customers.go new file mode 100644 index 0000000..c7609af --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/list_customers.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListCustomersHandlerFunc turns a function with the right signature into a list customers handler +type ListCustomersHandlerFunc func(ListCustomersParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListCustomersHandlerFunc) Handle(params ListCustomersParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListCustomersHandler interface for that can handle valid list customers params +type ListCustomersHandler interface { + Handle(ListCustomersParams, interface{}) middleware.Responder +} + +// NewListCustomers creates a new http.Handler for the list customers operation +func NewListCustomers(ctx *middleware.Context, handler ListCustomersHandler) *ListCustomers { + return &ListCustomers{Context: ctx, Handler: handler} +} + +/*ListCustomers swagger:route GET /customer customerManagement listCustomers + +List all the customers in the system + +*/ +type ListCustomers struct { + Context *middleware.Context + Handler ListCustomersHandler +} + +func (o *ListCustomers) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListCustomersParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/customer_management/list_customers_parameters.go b/services/customerdb/restapi/operations/customer_management/list_customers_parameters.go new file mode 100644 index 0000000..b31acb7 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/list_customers_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListCustomersParams creates a new ListCustomersParams object +// no default values defined in spec. +func NewListCustomersParams() ListCustomersParams { + + return ListCustomersParams{} +} + +// ListCustomersParams contains all the bound params for the list customers operation +// typically these are obtained from a http.Request +// +// swagger:parameters listCustomers +type ListCustomersParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListCustomersParams() beforehand. +func (o *ListCustomersParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/customer_management/list_customers_responses.go b/services/customerdb/restapi/operations/customer_management/list_customers_responses.go new file mode 100644 index 0000000..11dd5f5 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/list_customers_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ListCustomersOKCode is the HTTP code returned for type ListCustomersOK +const ListCustomersOKCode int = 200 + +/*ListCustomersOK List of customers in the system returned + +swagger:response listCustomersOK +*/ +type ListCustomersOK struct { + + /* + In: Body + */ + Payload []*models.Customer `json:"body,omitempty"` +} + +// NewListCustomersOK creates ListCustomersOK with default headers values +func NewListCustomersOK() *ListCustomersOK { + + return &ListCustomersOK{} +} + +// WithPayload adds the payload to the list customers o k response +func (o *ListCustomersOK) WithPayload(payload []*models.Customer) *ListCustomersOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list customers o k response +func (o *ListCustomersOK) SetPayload(payload []*models.Customer) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCustomersOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Customer, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListCustomersInternalServerErrorCode is the HTTP code returned for type ListCustomersInternalServerError +const ListCustomersInternalServerErrorCode int = 500 + +/*ListCustomersInternalServerError Something unexpected happend, error raised + +swagger:response listCustomersInternalServerError +*/ +type ListCustomersInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListCustomersInternalServerError creates ListCustomersInternalServerError with default headers values +func NewListCustomersInternalServerError() *ListCustomersInternalServerError { + + return &ListCustomersInternalServerError{} +} + +// WithPayload adds the payload to the list customers internal server error response +func (o *ListCustomersInternalServerError) WithPayload(payload *models.ErrorResponse) *ListCustomersInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list customers internal server error response +func (o *ListCustomersInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCustomersInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/customer_management/list_customers_urlbuilder.go b/services/customerdb/restapi/operations/customer_management/list_customers_urlbuilder.go new file mode 100644 index 0000000..b0d1ff6 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/list_customers_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListCustomersURL generates an URL for the list customers operation +type ListCustomersURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCustomersURL) WithBasePath(bp string) *ListCustomersURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCustomersURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListCustomersURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/customer" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListCustomersURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListCustomersURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListCustomersURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListCustomersURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListCustomersURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListCustomersURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/customer_management/update_customer.go b/services/customerdb/restapi/operations/customer_management/update_customer.go new file mode 100644 index 0000000..64582fa --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/update_customer.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdateCustomerHandlerFunc turns a function with the right signature into a update customer handler +type UpdateCustomerHandlerFunc func(UpdateCustomerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateCustomerHandlerFunc) Handle(params UpdateCustomerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdateCustomerHandler interface for that can handle valid update customer params +type UpdateCustomerHandler interface { + Handle(UpdateCustomerParams, interface{}) middleware.Responder +} + +// NewUpdateCustomer creates a new http.Handler for the update customer operation +func NewUpdateCustomer(ctx *middleware.Context, handler UpdateCustomerHandler) *UpdateCustomer { + return &UpdateCustomer{Context: ctx, Handler: handler} +} + +/*UpdateCustomer swagger:route PUT /customer/{id} customerManagement updateCustomer + +Updates the information of the customer with the given id + +*/ +type UpdateCustomer struct { + Context *middleware.Context + Handler UpdateCustomerHandler +} + +func (o *UpdateCustomer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateCustomerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/customer_management/update_customer_parameters.go b/services/customerdb/restapi/operations/customer_management/update_customer_parameters.go new file mode 100644 index 0000000..817a619 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/update_customer_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewUpdateCustomerParams creates a new UpdateCustomerParams object +// no default values defined in spec. +func NewUpdateCustomerParams() UpdateCustomerParams { + + return UpdateCustomerParams{} +} + +// UpdateCustomerParams contains all the bound params for the update customer operation +// typically these are obtained from a http.Request +// +// swagger:parameters updateCustomer +type UpdateCustomerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Customer to be updated + Required: true + In: body + */ + Customer *models.Customer + /*Id of the customer to be updated + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateCustomerParams() beforehand. +func (o *UpdateCustomerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Customer + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("customer", "body", "")) + } else { + res = append(res, errors.NewParseError("customer", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Customer = &body + } + } + } else { + res = append(res, errors.Required("customer", "body", "")) + } + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdateCustomerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/customerdb/restapi/operations/customer_management/update_customer_responses.go b/services/customerdb/restapi/operations/customer_management/update_customer_responses.go new file mode 100644 index 0000000..e2bbb6d --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/update_customer_responses.go @@ -0,0 +1,190 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// UpdateCustomerOKCode is the HTTP code returned for type UpdateCustomerOK +const UpdateCustomerOKCode int = 200 + +/*UpdateCustomerOK Customer with the given id was updated + +swagger:response updateCustomerOK +*/ +type UpdateCustomerOK struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewUpdateCustomerOK creates UpdateCustomerOK with default headers values +func NewUpdateCustomerOK() *UpdateCustomerOK { + + return &UpdateCustomerOK{} +} + +// WithPayload adds the payload to the update customer o k response +func (o *UpdateCustomerOK) WithPayload(payload *models.ItemCreatedResponse) *UpdateCustomerOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update customer o k response +func (o *UpdateCustomerOK) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateCustomerOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateCustomerAcceptedCode is the HTTP code returned for type UpdateCustomerAccepted +const UpdateCustomerAcceptedCode int = 202 + +/*UpdateCustomerAccepted The customer was updated but there might have been some fails when adding part of the data + +swagger:response updateCustomerAccepted +*/ +type UpdateCustomerAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewUpdateCustomerAccepted creates UpdateCustomerAccepted with default headers values +func NewUpdateCustomerAccepted() *UpdateCustomerAccepted { + + return &UpdateCustomerAccepted{} +} + +// WithPayload adds the payload to the update customer accepted response +func (o *UpdateCustomerAccepted) WithPayload(payload *models.ItemCreatedResponse) *UpdateCustomerAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update customer accepted response +func (o *UpdateCustomerAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateCustomerAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateCustomerNotFoundCode is the HTTP code returned for type UpdateCustomerNotFound +const UpdateCustomerNotFoundCode int = 404 + +/*UpdateCustomerNotFound The customer with the given id wasn't found + +swagger:response updateCustomerNotFound +*/ +type UpdateCustomerNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateCustomerNotFound creates UpdateCustomerNotFound with default headers values +func NewUpdateCustomerNotFound() *UpdateCustomerNotFound { + + return &UpdateCustomerNotFound{} +} + +// WithPayload adds the payload to the update customer not found response +func (o *UpdateCustomerNotFound) WithPayload(payload *models.ErrorResponse) *UpdateCustomerNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update customer not found response +func (o *UpdateCustomerNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateCustomerNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateCustomerInternalServerErrorCode is the HTTP code returned for type UpdateCustomerInternalServerError +const UpdateCustomerInternalServerErrorCode int = 500 + +/*UpdateCustomerInternalServerError Something unexpected happend, error raised + +swagger:response updateCustomerInternalServerError +*/ +type UpdateCustomerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateCustomerInternalServerError creates UpdateCustomerInternalServerError with default headers values +func NewUpdateCustomerInternalServerError() *UpdateCustomerInternalServerError { + + return &UpdateCustomerInternalServerError{} +} + +// WithPayload adds the payload to the update customer internal server error response +func (o *UpdateCustomerInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdateCustomerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update customer internal server error response +func (o *UpdateCustomerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateCustomerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/customer_management/update_customer_urlbuilder.go b/services/customerdb/restapi/operations/customer_management/update_customer_urlbuilder.go new file mode 100644 index 0000000..e9ce619 --- /dev/null +++ b/services/customerdb/restapi/operations/customer_management/update_customer_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package customer_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdateCustomerURL generates an URL for the update customer operation +type UpdateCustomerURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateCustomerURL) WithBasePath(bp string) *UpdateCustomerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateCustomerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateCustomerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/customer/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdateCustomerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateCustomerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateCustomerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateCustomerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateCustomerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateCustomerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateCustomerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/product_management/add_product.go b/services/customerdb/restapi/operations/product_management/add_product.go new file mode 100644 index 0000000..fce58fe --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/add_product.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// AddProductHandlerFunc turns a function with the right signature into a add product handler +type AddProductHandlerFunc func(AddProductParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn AddProductHandlerFunc) Handle(params AddProductParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// AddProductHandler interface for that can handle valid add product params +type AddProductHandler interface { + Handle(AddProductParams, interface{}) middleware.Responder +} + +// NewAddProduct creates a new http.Handler for the add product operation +func NewAddProduct(ctx *middleware.Context, handler AddProductHandler) *AddProduct { + return &AddProduct{Context: ctx, Handler: handler} +} + +/*AddProduct swagger:route POST /product productManagement addProduct + +Insert a new product in the system. + +*/ +type AddProduct struct { + Context *middleware.Context + Handler AddProductHandler +} + +func (o *AddProduct) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewAddProductParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/product_management/add_product_parameters.go b/services/customerdb/restapi/operations/product_management/add_product_parameters.go new file mode 100644 index 0000000..3bc005b --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/add_product_parameters.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewAddProductParams creates a new AddProductParams object +// no default values defined in spec. +func NewAddProductParams() AddProductParams { + + return AddProductParams{} +} + +// AddProductParams contains all the bound params for the add product operation +// typically these are obtained from a http.Request +// +// swagger:parameters addProduct +type AddProductParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Product to be added + Required: true + In: body + */ + Product *models.Product +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewAddProductParams() beforehand. +func (o *AddProductParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Product + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("product", "body", "")) + } else { + res = append(res, errors.NewParseError("product", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Product = &body + } + } + } else { + res = append(res, errors.Required("product", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/product_management/add_product_responses.go b/services/customerdb/restapi/operations/product_management/add_product_responses.go new file mode 100644 index 0000000..e150952 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/add_product_responses.go @@ -0,0 +1,170 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// AddProductCreatedCode is the HTTP code returned for type AddProductCreated +const AddProductCreatedCode int = 201 + +/*AddProductCreated New product was added successfully + +swagger:response addProductCreated +*/ +type AddProductCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewAddProductCreated creates AddProductCreated with default headers values +func NewAddProductCreated() *AddProductCreated { + + return &AddProductCreated{} +} + +// WithPayload adds the payload to the add product created response +func (o *AddProductCreated) WithPayload(payload *models.ItemCreatedResponse) *AddProductCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add product created response +func (o *AddProductCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddProductCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddProductBadRequestCode is the HTTP code returned for type AddProductBadRequest +const AddProductBadRequestCode int = 400 + +/*AddProductBadRequest Invalid input, object invalid + +swagger:response addProductBadRequest +*/ +type AddProductBadRequest struct { +} + +// NewAddProductBadRequest creates AddProductBadRequest with default headers values +func NewAddProductBadRequest() *AddProductBadRequest { + + return &AddProductBadRequest{} +} + +// WriteResponse to the client +func (o *AddProductBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// AddProductConflictCode is the HTTP code returned for type AddProductConflict +const AddProductConflictCode int = 409 + +/*AddProductConflict The given item already exists + +swagger:response addProductConflict +*/ +type AddProductConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddProductConflict creates AddProductConflict with default headers values +func NewAddProductConflict() *AddProductConflict { + + return &AddProductConflict{} +} + +// WithPayload adds the payload to the add product conflict response +func (o *AddProductConflict) WithPayload(payload *models.ErrorResponse) *AddProductConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add product conflict response +func (o *AddProductConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddProductConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddProductInternalServerErrorCode is the HTTP code returned for type AddProductInternalServerError +const AddProductInternalServerErrorCode int = 500 + +/*AddProductInternalServerError Something unexpected happend, error raised + +swagger:response addProductInternalServerError +*/ +type AddProductInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddProductInternalServerError creates AddProductInternalServerError with default headers values +func NewAddProductInternalServerError() *AddProductInternalServerError { + + return &AddProductInternalServerError{} +} + +// WithPayload adds the payload to the add product internal server error response +func (o *AddProductInternalServerError) WithPayload(payload *models.ErrorResponse) *AddProductInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add product internal server error response +func (o *AddProductInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddProductInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/product_management/add_product_urlbuilder.go b/services/customerdb/restapi/operations/product_management/add_product_urlbuilder.go new file mode 100644 index 0000000..40d41bb --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/add_product_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// AddProductURL generates an URL for the add product operation +type AddProductURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddProductURL) WithBasePath(bp string) *AddProductURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddProductURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *AddProductURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/product" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *AddProductURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *AddProductURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *AddProductURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on AddProductURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on AddProductURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *AddProductURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/product_management/get_product.go b/services/customerdb/restapi/operations/product_management/get_product.go new file mode 100644 index 0000000..6890178 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/get_product.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetProductHandlerFunc turns a function with the right signature into a get product handler +type GetProductHandlerFunc func(GetProductParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetProductHandlerFunc) Handle(params GetProductParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetProductHandler interface for that can handle valid get product params +type GetProductHandler interface { + Handle(GetProductParams, interface{}) middleware.Responder +} + +// NewGetProduct creates a new http.Handler for the get product operation +func NewGetProduct(ctx *middleware.Context, handler GetProductHandler) *GetProduct { + return &GetProduct{Context: ctx, Handler: handler} +} + +/*GetProduct swagger:route GET /product/{id} productManagement getProduct + +Return the information about the product with the given id + +*/ +type GetProduct struct { + Context *middleware.Context + Handler GetProductHandler +} + +func (o *GetProduct) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetProductParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/product_management/get_product_parameters.go b/services/customerdb/restapi/operations/product_management/get_product_parameters.go new file mode 100644 index 0000000..1d45f64 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/get_product_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetProductParams creates a new GetProductParams object +// no default values defined in spec. +func NewGetProductParams() GetProductParams { + + return GetProductParams{} +} + +// GetProductParams contains all the bound params for the get product operation +// typically these are obtained from a http.Request +// +// swagger:parameters getProduct +type GetProductParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the product to be retrieved + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetProductParams() beforehand. +func (o *GetProductParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetProductParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/customerdb/restapi/operations/product_management/get_product_responses.go b/services/customerdb/restapi/operations/product_management/get_product_responses.go new file mode 100644 index 0000000..d9978d3 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/get_product_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetProductOKCode is the HTTP code returned for type GetProductOK +const GetProductOKCode int = 200 + +/*GetProductOK Product with the id given in the system returned + +swagger:response getProductOK +*/ +type GetProductOK struct { + + /* + In: Body + */ + Payload *models.Product `json:"body,omitempty"` +} + +// NewGetProductOK creates GetProductOK with default headers values +func NewGetProductOK() *GetProductOK { + + return &GetProductOK{} +} + +// WithPayload adds the payload to the get product o k response +func (o *GetProductOK) WithPayload(payload *models.Product) *GetProductOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get product o k response +func (o *GetProductOK) SetPayload(payload *models.Product) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetProductOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetProductNotFoundCode is the HTTP code returned for type GetProductNotFound +const GetProductNotFoundCode int = 404 + +/*GetProductNotFound The product with the given id wasn't found + +swagger:response getProductNotFound +*/ +type GetProductNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetProductNotFound creates GetProductNotFound with default headers values +func NewGetProductNotFound() *GetProductNotFound { + + return &GetProductNotFound{} +} + +// WithPayload adds the payload to the get product not found response +func (o *GetProductNotFound) WithPayload(payload *models.ErrorResponse) *GetProductNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get product not found response +func (o *GetProductNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetProductNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetProductInternalServerErrorCode is the HTTP code returned for type GetProductInternalServerError +const GetProductInternalServerErrorCode int = 500 + +/*GetProductInternalServerError Something unexpected happend, error raised + +swagger:response getProductInternalServerError +*/ +type GetProductInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetProductInternalServerError creates GetProductInternalServerError with default headers values +func NewGetProductInternalServerError() *GetProductInternalServerError { + + return &GetProductInternalServerError{} +} + +// WithPayload adds the payload to the get product internal server error response +func (o *GetProductInternalServerError) WithPayload(payload *models.ErrorResponse) *GetProductInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get product internal server error response +func (o *GetProductInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetProductInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/product_management/get_product_urlbuilder.go b/services/customerdb/restapi/operations/product_management/get_product_urlbuilder.go new file mode 100644 index 0000000..cd447fd --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/get_product_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetProductURL generates an URL for the get product operation +type GetProductURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetProductURL) WithBasePath(bp string) *GetProductURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetProductURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetProductURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/product/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetProductURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetProductURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetProductURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetProductURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetProductURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetProductURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetProductURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/product_management/list_products.go b/services/customerdb/restapi/operations/product_management/list_products.go new file mode 100644 index 0000000..8d97e8e --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/list_products.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListProductsHandlerFunc turns a function with the right signature into a list products handler +type ListProductsHandlerFunc func(ListProductsParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListProductsHandlerFunc) Handle(params ListProductsParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListProductsHandler interface for that can handle valid list products params +type ListProductsHandler interface { + Handle(ListProductsParams, interface{}) middleware.Responder +} + +// NewListProducts creates a new http.Handler for the list products operation +func NewListProducts(ctx *middleware.Context, handler ListProductsHandler) *ListProducts { + return &ListProducts{Context: ctx, Handler: handler} +} + +/*ListProducts swagger:route GET /product productManagement listProducts + +List all the products in the system + +*/ +type ListProducts struct { + Context *middleware.Context + Handler ListProductsHandler +} + +func (o *ListProducts) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListProductsParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/product_management/list_products_parameters.go b/services/customerdb/restapi/operations/product_management/list_products_parameters.go new file mode 100644 index 0000000..0217e19 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/list_products_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListProductsParams creates a new ListProductsParams object +// no default values defined in spec. +func NewListProductsParams() ListProductsParams { + + return ListProductsParams{} +} + +// ListProductsParams contains all the bound params for the list products operation +// typically these are obtained from a http.Request +// +// swagger:parameters listProducts +type ListProductsParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListProductsParams() beforehand. +func (o *ListProductsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/product_management/list_products_responses.go b/services/customerdb/restapi/operations/product_management/list_products_responses.go new file mode 100644 index 0000000..2770111 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/list_products_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ListProductsOKCode is the HTTP code returned for type ListProductsOK +const ListProductsOKCode int = 200 + +/*ListProductsOK List of products in the system returned + +swagger:response listProductsOK +*/ +type ListProductsOK struct { + + /* + In: Body + */ + Payload []*models.Product `json:"body,omitempty"` +} + +// NewListProductsOK creates ListProductsOK with default headers values +func NewListProductsOK() *ListProductsOK { + + return &ListProductsOK{} +} + +// WithPayload adds the payload to the list products o k response +func (o *ListProductsOK) WithPayload(payload []*models.Product) *ListProductsOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list products o k response +func (o *ListProductsOK) SetPayload(payload []*models.Product) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListProductsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Product, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListProductsInternalServerErrorCode is the HTTP code returned for type ListProductsInternalServerError +const ListProductsInternalServerErrorCode int = 500 + +/*ListProductsInternalServerError Something unexpected happend, error raised + +swagger:response listProductsInternalServerError +*/ +type ListProductsInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListProductsInternalServerError creates ListProductsInternalServerError with default headers values +func NewListProductsInternalServerError() *ListProductsInternalServerError { + + return &ListProductsInternalServerError{} +} + +// WithPayload adds the payload to the list products internal server error response +func (o *ListProductsInternalServerError) WithPayload(payload *models.ErrorResponse) *ListProductsInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list products internal server error response +func (o *ListProductsInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListProductsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/product_management/list_products_urlbuilder.go b/services/customerdb/restapi/operations/product_management/list_products_urlbuilder.go new file mode 100644 index 0000000..cbb16aa --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/list_products_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListProductsURL generates an URL for the list products operation +type ListProductsURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListProductsURL) WithBasePath(bp string) *ListProductsURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListProductsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListProductsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/product" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListProductsURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListProductsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListProductsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListProductsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListProductsURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListProductsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/product_management/update_product.go b/services/customerdb/restapi/operations/product_management/update_product.go new file mode 100644 index 0000000..aa8aadb --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/update_product.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdateProductHandlerFunc turns a function with the right signature into a update product handler +type UpdateProductHandlerFunc func(UpdateProductParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateProductHandlerFunc) Handle(params UpdateProductParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdateProductHandler interface for that can handle valid update product params +type UpdateProductHandler interface { + Handle(UpdateProductParams, interface{}) middleware.Responder +} + +// NewUpdateProduct creates a new http.Handler for the update product operation +func NewUpdateProduct(ctx *middleware.Context, handler UpdateProductHandler) *UpdateProduct { + return &UpdateProduct{Context: ctx, Handler: handler} +} + +/*UpdateProduct swagger:route PUT /product/{id} productManagement updateProduct + +Updates the information of the product with the given id + +*/ +type UpdateProduct struct { + Context *middleware.Context + Handler UpdateProductHandler +} + +func (o *UpdateProduct) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateProductParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/product_management/update_product_parameters.go b/services/customerdb/restapi/operations/product_management/update_product_parameters.go new file mode 100644 index 0000000..86a75b3 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/update_product_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewUpdateProductParams creates a new UpdateProductParams object +// no default values defined in spec. +func NewUpdateProductParams() UpdateProductParams { + + return UpdateProductParams{} +} + +// UpdateProductParams contains all the bound params for the update product operation +// typically these are obtained from a http.Request +// +// swagger:parameters updateProduct +type UpdateProductParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the product to be updated + Required: true + In: path + */ + ID string + /*Product to be updated + Required: true + In: body + */ + Product *models.Product +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateProductParams() beforehand. +func (o *UpdateProductParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Product + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("product", "body", "")) + } else { + res = append(res, errors.NewParseError("product", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Product = &body + } + } + } else { + res = append(res, errors.Required("product", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdateProductParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/customerdb/restapi/operations/product_management/update_product_responses.go b/services/customerdb/restapi/operations/product_management/update_product_responses.go new file mode 100644 index 0000000..c2f2f0d --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/update_product_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// UpdateProductOKCode is the HTTP code returned for type UpdateProductOK +const UpdateProductOKCode int = 200 + +/*UpdateProductOK Product with the given id was updated + +swagger:response updateProductOK +*/ +type UpdateProductOK struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewUpdateProductOK creates UpdateProductOK with default headers values +func NewUpdateProductOK() *UpdateProductOK { + + return &UpdateProductOK{} +} + +// WithPayload adds the payload to the update product o k response +func (o *UpdateProductOK) WithPayload(payload *models.ItemCreatedResponse) *UpdateProductOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update product o k response +func (o *UpdateProductOK) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateProductOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateProductNotFoundCode is the HTTP code returned for type UpdateProductNotFound +const UpdateProductNotFoundCode int = 404 + +/*UpdateProductNotFound The product with the given id wasn't found + +swagger:response updateProductNotFound +*/ +type UpdateProductNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateProductNotFound creates UpdateProductNotFound with default headers values +func NewUpdateProductNotFound() *UpdateProductNotFound { + + return &UpdateProductNotFound{} +} + +// WithPayload adds the payload to the update product not found response +func (o *UpdateProductNotFound) WithPayload(payload *models.ErrorResponse) *UpdateProductNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update product not found response +func (o *UpdateProductNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateProductNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateProductInternalServerErrorCode is the HTTP code returned for type UpdateProductInternalServerError +const UpdateProductInternalServerErrorCode int = 500 + +/*UpdateProductInternalServerError Something unexpected happend, error raised + +swagger:response updateProductInternalServerError +*/ +type UpdateProductInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateProductInternalServerError creates UpdateProductInternalServerError with default headers values +func NewUpdateProductInternalServerError() *UpdateProductInternalServerError { + + return &UpdateProductInternalServerError{} +} + +// WithPayload adds the payload to the update product internal server error response +func (o *UpdateProductInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdateProductInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update product internal server error response +func (o *UpdateProductInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateProductInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/product_management/update_product_urlbuilder.go b/services/customerdb/restapi/operations/product_management/update_product_urlbuilder.go new file mode 100644 index 0000000..6078490 --- /dev/null +++ b/services/customerdb/restapi/operations/product_management/update_product_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package product_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdateProductURL generates an URL for the update product operation +type UpdateProductURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateProductURL) WithBasePath(bp string) *UpdateProductURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateProductURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateProductURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/product/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdateProductURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateProductURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateProductURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateProductURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateProductURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateProductURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateProductURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/reseller_management/add_reseller.go b/services/customerdb/restapi/operations/reseller_management/add_reseller.go new file mode 100644 index 0000000..92f40a6 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/add_reseller.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// AddResellerHandlerFunc turns a function with the right signature into a add reseller handler +type AddResellerHandlerFunc func(AddResellerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn AddResellerHandlerFunc) Handle(params AddResellerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// AddResellerHandler interface for that can handle valid add reseller params +type AddResellerHandler interface { + Handle(AddResellerParams, interface{}) middleware.Responder +} + +// NewAddReseller creates a new http.Handler for the add reseller operation +func NewAddReseller(ctx *middleware.Context, handler AddResellerHandler) *AddReseller { + return &AddReseller{Context: ctx, Handler: handler} +} + +/*AddReseller swagger:route POST /reseller resellerManagement addReseller + +Insert a new reseller in the system. + +*/ +type AddReseller struct { + Context *middleware.Context + Handler AddResellerHandler +} + +func (o *AddReseller) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewAddResellerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/reseller_management/add_reseller_parameters.go b/services/customerdb/restapi/operations/reseller_management/add_reseller_parameters.go new file mode 100644 index 0000000..34968cc --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/add_reseller_parameters.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewAddResellerParams creates a new AddResellerParams object +// no default values defined in spec. +func NewAddResellerParams() AddResellerParams { + + return AddResellerParams{} +} + +// AddResellerParams contains all the bound params for the add reseller operation +// typically these are obtained from a http.Request +// +// swagger:parameters addReseller +type AddResellerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Reseller to be added + Required: true + In: body + */ + Reseller *models.Reseller +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewAddResellerParams() beforehand. +func (o *AddResellerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Reseller + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("reseller", "body", "")) + } else { + res = append(res, errors.NewParseError("reseller", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Reseller = &body + } + } + } else { + res = append(res, errors.Required("reseller", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/reseller_management/add_reseller_responses.go b/services/customerdb/restapi/operations/reseller_management/add_reseller_responses.go new file mode 100644 index 0000000..6f16798 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/add_reseller_responses.go @@ -0,0 +1,214 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// AddResellerCreatedCode is the HTTP code returned for type AddResellerCreated +const AddResellerCreatedCode int = 201 + +/*AddResellerCreated New reseller was added successfully + +swagger:response addResellerCreated +*/ +type AddResellerCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewAddResellerCreated creates AddResellerCreated with default headers values +func NewAddResellerCreated() *AddResellerCreated { + + return &AddResellerCreated{} +} + +// WithPayload adds the payload to the add reseller created response +func (o *AddResellerCreated) WithPayload(payload *models.ItemCreatedResponse) *AddResellerCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add reseller created response +func (o *AddResellerCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddResellerCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddResellerAcceptedCode is the HTTP code returned for type AddResellerAccepted +const AddResellerAcceptedCode int = 202 + +/*AddResellerAccepted The new reseller was added but there might have been some fails when adding part of the data + +swagger:response addResellerAccepted +*/ +type AddResellerAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewAddResellerAccepted creates AddResellerAccepted with default headers values +func NewAddResellerAccepted() *AddResellerAccepted { + + return &AddResellerAccepted{} +} + +// WithPayload adds the payload to the add reseller accepted response +func (o *AddResellerAccepted) WithPayload(payload *models.ItemCreatedResponse) *AddResellerAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add reseller accepted response +func (o *AddResellerAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddResellerAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddResellerBadRequestCode is the HTTP code returned for type AddResellerBadRequest +const AddResellerBadRequestCode int = 400 + +/*AddResellerBadRequest Invalid input, object invalid + +swagger:response addResellerBadRequest +*/ +type AddResellerBadRequest struct { +} + +// NewAddResellerBadRequest creates AddResellerBadRequest with default headers values +func NewAddResellerBadRequest() *AddResellerBadRequest { + + return &AddResellerBadRequest{} +} + +// WriteResponse to the client +func (o *AddResellerBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// AddResellerConflictCode is the HTTP code returned for type AddResellerConflict +const AddResellerConflictCode int = 409 + +/*AddResellerConflict The given item already exists + +swagger:response addResellerConflict +*/ +type AddResellerConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddResellerConflict creates AddResellerConflict with default headers values +func NewAddResellerConflict() *AddResellerConflict { + + return &AddResellerConflict{} +} + +// WithPayload adds the payload to the add reseller conflict response +func (o *AddResellerConflict) WithPayload(payload *models.ErrorResponse) *AddResellerConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add reseller conflict response +func (o *AddResellerConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddResellerConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddResellerInternalServerErrorCode is the HTTP code returned for type AddResellerInternalServerError +const AddResellerInternalServerErrorCode int = 500 + +/*AddResellerInternalServerError Something unexpected happend, error raised + +swagger:response addResellerInternalServerError +*/ +type AddResellerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddResellerInternalServerError creates AddResellerInternalServerError with default headers values +func NewAddResellerInternalServerError() *AddResellerInternalServerError { + + return &AddResellerInternalServerError{} +} + +// WithPayload adds the payload to the add reseller internal server error response +func (o *AddResellerInternalServerError) WithPayload(payload *models.ErrorResponse) *AddResellerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add reseller internal server error response +func (o *AddResellerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddResellerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/reseller_management/add_reseller_urlbuilder.go b/services/customerdb/restapi/operations/reseller_management/add_reseller_urlbuilder.go new file mode 100644 index 0000000..8bcdb46 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/add_reseller_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// AddResellerURL generates an URL for the add reseller operation +type AddResellerURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddResellerURL) WithBasePath(bp string) *AddResellerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddResellerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *AddResellerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/reseller" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *AddResellerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *AddResellerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *AddResellerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on AddResellerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on AddResellerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *AddResellerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/reseller_management/get_reseller.go b/services/customerdb/restapi/operations/reseller_management/get_reseller.go new file mode 100644 index 0000000..2662638 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/get_reseller.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetResellerHandlerFunc turns a function with the right signature into a get reseller handler +type GetResellerHandlerFunc func(GetResellerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetResellerHandlerFunc) Handle(params GetResellerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetResellerHandler interface for that can handle valid get reseller params +type GetResellerHandler interface { + Handle(GetResellerParams, interface{}) middleware.Responder +} + +// NewGetReseller creates a new http.Handler for the get reseller operation +func NewGetReseller(ctx *middleware.Context, handler GetResellerHandler) *GetReseller { + return &GetReseller{Context: ctx, Handler: handler} +} + +/*GetReseller swagger:route GET /reseller/{id} resellerManagement getReseller + +Return the information about the reseller with the given id + +*/ +type GetReseller struct { + Context *middleware.Context + Handler GetResellerHandler +} + +func (o *GetReseller) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetResellerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/reseller_management/get_reseller_parameters.go b/services/customerdb/restapi/operations/reseller_management/get_reseller_parameters.go new file mode 100644 index 0000000..e796a6b --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/get_reseller_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetResellerParams creates a new GetResellerParams object +// no default values defined in spec. +func NewGetResellerParams() GetResellerParams { + + return GetResellerParams{} +} + +// GetResellerParams contains all the bound params for the get reseller operation +// typically these are obtained from a http.Request +// +// swagger:parameters getReseller +type GetResellerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the reseller to be retrieved + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetResellerParams() beforehand. +func (o *GetResellerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetResellerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/customerdb/restapi/operations/reseller_management/get_reseller_responses.go b/services/customerdb/restapi/operations/reseller_management/get_reseller_responses.go new file mode 100644 index 0000000..425804b --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/get_reseller_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetResellerOKCode is the HTTP code returned for type GetResellerOK +const GetResellerOKCode int = 200 + +/*GetResellerOK Reseller with the id given in the system returned + +swagger:response getResellerOK +*/ +type GetResellerOK struct { + + /* + In: Body + */ + Payload *models.Reseller `json:"body,omitempty"` +} + +// NewGetResellerOK creates GetResellerOK with default headers values +func NewGetResellerOK() *GetResellerOK { + + return &GetResellerOK{} +} + +// WithPayload adds the payload to the get reseller o k response +func (o *GetResellerOK) WithPayload(payload *models.Reseller) *GetResellerOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get reseller o k response +func (o *GetResellerOK) SetPayload(payload *models.Reseller) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetResellerOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetResellerNotFoundCode is the HTTP code returned for type GetResellerNotFound +const GetResellerNotFoundCode int = 404 + +/*GetResellerNotFound The reseller with the given id wasn't found + +swagger:response getResellerNotFound +*/ +type GetResellerNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetResellerNotFound creates GetResellerNotFound with default headers values +func NewGetResellerNotFound() *GetResellerNotFound { + + return &GetResellerNotFound{} +} + +// WithPayload adds the payload to the get reseller not found response +func (o *GetResellerNotFound) WithPayload(payload *models.ErrorResponse) *GetResellerNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get reseller not found response +func (o *GetResellerNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetResellerNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetResellerInternalServerErrorCode is the HTTP code returned for type GetResellerInternalServerError +const GetResellerInternalServerErrorCode int = 500 + +/*GetResellerInternalServerError Something unexpected happend, error raised + +swagger:response getResellerInternalServerError +*/ +type GetResellerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetResellerInternalServerError creates GetResellerInternalServerError with default headers values +func NewGetResellerInternalServerError() *GetResellerInternalServerError { + + return &GetResellerInternalServerError{} +} + +// WithPayload adds the payload to the get reseller internal server error response +func (o *GetResellerInternalServerError) WithPayload(payload *models.ErrorResponse) *GetResellerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get reseller internal server error response +func (o *GetResellerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetResellerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/reseller_management/get_reseller_urlbuilder.go b/services/customerdb/restapi/operations/reseller_management/get_reseller_urlbuilder.go new file mode 100644 index 0000000..9f35b97 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/get_reseller_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetResellerURL generates an URL for the get reseller operation +type GetResellerURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetResellerURL) WithBasePath(bp string) *GetResellerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetResellerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetResellerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/reseller/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetResellerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetResellerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetResellerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetResellerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetResellerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetResellerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetResellerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/reseller_management/list_resellers.go b/services/customerdb/restapi/operations/reseller_management/list_resellers.go new file mode 100644 index 0000000..240645f --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/list_resellers.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListResellersHandlerFunc turns a function with the right signature into a list resellers handler +type ListResellersHandlerFunc func(ListResellersParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListResellersHandlerFunc) Handle(params ListResellersParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListResellersHandler interface for that can handle valid list resellers params +type ListResellersHandler interface { + Handle(ListResellersParams, interface{}) middleware.Responder +} + +// NewListResellers creates a new http.Handler for the list resellers operation +func NewListResellers(ctx *middleware.Context, handler ListResellersHandler) *ListResellers { + return &ListResellers{Context: ctx, Handler: handler} +} + +/*ListResellers swagger:route GET /reseller resellerManagement listResellers + +List all the resellers in the system + +*/ +type ListResellers struct { + Context *middleware.Context + Handler ListResellersHandler +} + +func (o *ListResellers) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListResellersParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/reseller_management/list_resellers_parameters.go b/services/customerdb/restapi/operations/reseller_management/list_resellers_parameters.go new file mode 100644 index 0000000..250e6bc --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/list_resellers_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListResellersParams creates a new ListResellersParams object +// no default values defined in spec. +func NewListResellersParams() ListResellersParams { + + return ListResellersParams{} +} + +// ListResellersParams contains all the bound params for the list resellers operation +// typically these are obtained from a http.Request +// +// swagger:parameters listResellers +type ListResellersParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListResellersParams() beforehand. +func (o *ListResellersParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/reseller_management/list_resellers_responses.go b/services/customerdb/restapi/operations/reseller_management/list_resellers_responses.go new file mode 100644 index 0000000..4f2d2a3 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/list_resellers_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ListResellersOKCode is the HTTP code returned for type ListResellersOK +const ListResellersOKCode int = 200 + +/*ListResellersOK List of resellers in the system returned + +swagger:response listResellersOK +*/ +type ListResellersOK struct { + + /* + In: Body + */ + Payload []*models.Reseller `json:"body,omitempty"` +} + +// NewListResellersOK creates ListResellersOK with default headers values +func NewListResellersOK() *ListResellersOK { + + return &ListResellersOK{} +} + +// WithPayload adds the payload to the list resellers o k response +func (o *ListResellersOK) WithPayload(payload []*models.Reseller) *ListResellersOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list resellers o k response +func (o *ListResellersOK) SetPayload(payload []*models.Reseller) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListResellersOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Reseller, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListResellersInternalServerErrorCode is the HTTP code returned for type ListResellersInternalServerError +const ListResellersInternalServerErrorCode int = 500 + +/*ListResellersInternalServerError Something unexpected happend, error raised + +swagger:response listResellersInternalServerError +*/ +type ListResellersInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListResellersInternalServerError creates ListResellersInternalServerError with default headers values +func NewListResellersInternalServerError() *ListResellersInternalServerError { + + return &ListResellersInternalServerError{} +} + +// WithPayload adds the payload to the list resellers internal server error response +func (o *ListResellersInternalServerError) WithPayload(payload *models.ErrorResponse) *ListResellersInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list resellers internal server error response +func (o *ListResellersInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListResellersInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/reseller_management/list_resellers_urlbuilder.go b/services/customerdb/restapi/operations/reseller_management/list_resellers_urlbuilder.go new file mode 100644 index 0000000..2c61e17 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/list_resellers_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListResellersURL generates an URL for the list resellers operation +type ListResellersURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListResellersURL) WithBasePath(bp string) *ListResellersURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListResellersURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListResellersURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/reseller" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListResellersURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListResellersURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListResellersURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListResellersURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListResellersURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListResellersURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/reseller_management/update_reseller.go b/services/customerdb/restapi/operations/reseller_management/update_reseller.go new file mode 100644 index 0000000..d33ac90 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/update_reseller.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdateResellerHandlerFunc turns a function with the right signature into a update reseller handler +type UpdateResellerHandlerFunc func(UpdateResellerParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateResellerHandlerFunc) Handle(params UpdateResellerParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdateResellerHandler interface for that can handle valid update reseller params +type UpdateResellerHandler interface { + Handle(UpdateResellerParams, interface{}) middleware.Responder +} + +// NewUpdateReseller creates a new http.Handler for the update reseller operation +func NewUpdateReseller(ctx *middleware.Context, handler UpdateResellerHandler) *UpdateReseller { + return &UpdateReseller{Context: ctx, Handler: handler} +} + +/*UpdateReseller swagger:route PUT /reseller/{id} resellerManagement updateReseller + +Updates the information of the reseller with the given id + +*/ +type UpdateReseller struct { + Context *middleware.Context + Handler UpdateResellerHandler +} + +func (o *UpdateReseller) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateResellerParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/reseller_management/update_reseller_parameters.go b/services/customerdb/restapi/operations/reseller_management/update_reseller_parameters.go new file mode 100644 index 0000000..09bff6d --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/update_reseller_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// NewUpdateResellerParams creates a new UpdateResellerParams object +// no default values defined in spec. +func NewUpdateResellerParams() UpdateResellerParams { + + return UpdateResellerParams{} +} + +// UpdateResellerParams contains all the bound params for the update reseller operation +// typically these are obtained from a http.Request +// +// swagger:parameters updateReseller +type UpdateResellerParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the reseller to be updated + Required: true + In: path + */ + ID string + /*Reseller to be updated + Required: true + In: body + */ + Reseller *models.Reseller +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateResellerParams() beforehand. +func (o *UpdateResellerParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Reseller + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("reseller", "body", "")) + } else { + res = append(res, errors.NewParseError("reseller", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Reseller = &body + } + } + } else { + res = append(res, errors.Required("reseller", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdateResellerParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/customerdb/restapi/operations/reseller_management/update_reseller_responses.go b/services/customerdb/restapi/operations/reseller_management/update_reseller_responses.go new file mode 100644 index 0000000..5a1c959 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/update_reseller_responses.go @@ -0,0 +1,190 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// UpdateResellerOKCode is the HTTP code returned for type UpdateResellerOK +const UpdateResellerOKCode int = 200 + +/*UpdateResellerOK Reseller with the given id was updated + +swagger:response updateResellerOK +*/ +type UpdateResellerOK struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewUpdateResellerOK creates UpdateResellerOK with default headers values +func NewUpdateResellerOK() *UpdateResellerOK { + + return &UpdateResellerOK{} +} + +// WithPayload adds the payload to the update reseller o k response +func (o *UpdateResellerOK) WithPayload(payload *models.ItemCreatedResponse) *UpdateResellerOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update reseller o k response +func (o *UpdateResellerOK) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateResellerOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateResellerAcceptedCode is the HTTP code returned for type UpdateResellerAccepted +const UpdateResellerAcceptedCode int = 202 + +/*UpdateResellerAccepted The reseller was updated but there might have been some fails when adding part of the data + +swagger:response updateResellerAccepted +*/ +type UpdateResellerAccepted struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewUpdateResellerAccepted creates UpdateResellerAccepted with default headers values +func NewUpdateResellerAccepted() *UpdateResellerAccepted { + + return &UpdateResellerAccepted{} +} + +// WithPayload adds the payload to the update reseller accepted response +func (o *UpdateResellerAccepted) WithPayload(payload *models.ItemCreatedResponse) *UpdateResellerAccepted { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update reseller accepted response +func (o *UpdateResellerAccepted) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateResellerAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(202) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateResellerNotFoundCode is the HTTP code returned for type UpdateResellerNotFound +const UpdateResellerNotFoundCode int = 404 + +/*UpdateResellerNotFound The reseller with the given id wasn't found + +swagger:response updateResellerNotFound +*/ +type UpdateResellerNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateResellerNotFound creates UpdateResellerNotFound with default headers values +func NewUpdateResellerNotFound() *UpdateResellerNotFound { + + return &UpdateResellerNotFound{} +} + +// WithPayload adds the payload to the update reseller not found response +func (o *UpdateResellerNotFound) WithPayload(payload *models.ErrorResponse) *UpdateResellerNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update reseller not found response +func (o *UpdateResellerNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateResellerNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateResellerInternalServerErrorCode is the HTTP code returned for type UpdateResellerInternalServerError +const UpdateResellerInternalServerErrorCode int = 500 + +/*UpdateResellerInternalServerError Something unexpected happend, error raised + +swagger:response updateResellerInternalServerError +*/ +type UpdateResellerInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateResellerInternalServerError creates UpdateResellerInternalServerError with default headers values +func NewUpdateResellerInternalServerError() *UpdateResellerInternalServerError { + + return &UpdateResellerInternalServerError{} +} + +// WithPayload adds the payload to the update reseller internal server error response +func (o *UpdateResellerInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdateResellerInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update reseller internal server error response +func (o *UpdateResellerInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateResellerInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/reseller_management/update_reseller_urlbuilder.go b/services/customerdb/restapi/operations/reseller_management/update_reseller_urlbuilder.go new file mode 100644 index 0000000..cc21650 --- /dev/null +++ b/services/customerdb/restapi/operations/reseller_management/update_reseller_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package reseller_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdateResellerURL generates an URL for the update reseller operation +type UpdateResellerURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateResellerURL) WithBasePath(bp string) *UpdateResellerURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateResellerURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateResellerURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/reseller/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdateResellerURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateResellerURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateResellerURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateResellerURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateResellerURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateResellerURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateResellerURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/status_management/get_status.go b/services/customerdb/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/status_management/get_status_parameters.go b/services/customerdb/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..67575fb --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the product to be retrieved + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"kafka-receiver", "kafka-sender", "status", "trigger", "customer", "product", "reseller"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/customerdb/restapi/operations/status_management/get_status_responses.go b/services/customerdb/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..e00de02 --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/status_management/get_status_urlbuilder.go b/services/customerdb/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..151ece5 --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/status_management/show_status.go b/services/customerdb/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/status_management/show_status_parameters.go b/services/customerdb/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/status_management/show_status_responses.go b/services/customerdb/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..a922e8e --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/status_management/show_status_urlbuilder.go b/services/customerdb/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..6efc165 --- /dev/null +++ b/services/customerdb/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/operations/trigger_management/exec_sample.go b/services/customerdb/restapi/operations/trigger_management/exec_sample.go new file mode 100644 index 0000000..3a21c8a --- /dev/null +++ b/services/customerdb/restapi/operations/trigger_management/exec_sample.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ExecSampleHandlerFunc turns a function with the right signature into a exec sample handler +type ExecSampleHandlerFunc func(ExecSampleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ExecSampleHandlerFunc) Handle(params ExecSampleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ExecSampleHandler interface for that can handle valid exec sample params +type ExecSampleHandler interface { + Handle(ExecSampleParams, interface{}) middleware.Responder +} + +// NewExecSample creates a new http.Handler for the exec sample operation +func NewExecSample(ctx *middleware.Context, handler ExecSampleHandler) *ExecSample { + return &ExecSample{Context: ctx, Handler: handler} +} + +/*ExecSample swagger:route GET /trigger/sample triggerManagement execSample + +Sample task trigger + +*/ +type ExecSample struct { + Context *middleware.Context + Handler ExecSampleHandler +} + +func (o *ExecSample) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewExecSampleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/customerdb/restapi/operations/trigger_management/exec_sample_parameters.go b/services/customerdb/restapi/operations/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..e3aad65 --- /dev/null +++ b/services/customerdb/restapi/operations/trigger_management/exec_sample_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// no default values defined in spec. +func NewExecSampleParams() ExecSampleParams { + + return ExecSampleParams{} +} + +// ExecSampleParams contains all the bound params for the exec sample operation +// typically these are obtained from a http.Request +// +// swagger:parameters execSample +type ExecSampleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewExecSampleParams() beforehand. +func (o *ExecSampleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/customerdb/restapi/operations/trigger_management/exec_sample_responses.go b/services/customerdb/restapi/operations/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..7b627c4 --- /dev/null +++ b/services/customerdb/restapi/operations/trigger_management/exec_sample_responses.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" +) + +// ExecSampleOKCode is the HTTP code returned for type ExecSampleOK +const ExecSampleOKCode int = 200 + +/*ExecSampleOK Sample task executed successfully + +swagger:response execSampleOK +*/ +type ExecSampleOK struct { +} + +// NewExecSampleOK creates ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + + return &ExecSampleOK{} +} + +// WriteResponse to the client +func (o *ExecSampleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// ExecSampleInternalServerErrorCode is the HTTP code returned for type ExecSampleInternalServerError +const ExecSampleInternalServerErrorCode int = 500 + +/*ExecSampleInternalServerError Something unexpected happend, error raised + +swagger:response execSampleInternalServerError +*/ +type ExecSampleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewExecSampleInternalServerError creates ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + + return &ExecSampleInternalServerError{} +} + +// WithPayload adds the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) WithPayload(payload *models.ErrorResponse) *ExecSampleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ExecSampleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/customerdb/restapi/operations/trigger_management/exec_sample_urlbuilder.go b/services/customerdb/restapi/operations/trigger_management/exec_sample_urlbuilder.go new file mode 100644 index 0000000..33b621a --- /dev/null +++ b/services/customerdb/restapi/operations/trigger_management/exec_sample_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ExecSampleURL generates an URL for the exec sample operation +type ExecSampleURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) WithBasePath(bp string) *ExecSampleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ExecSampleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/sample" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ExecSampleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ExecSampleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ExecSampleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ExecSampleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ExecSampleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ExecSampleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/customerdb/restapi/server.go b/services/customerdb/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/services/customerdb/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/services/customerdb/run/cert.crt b/services/customerdb/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/customerdb/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/customerdb/run/config.toml b/services/customerdb/run/config.toml new file mode 100644 index 0000000..1bd9381 --- /dev/null +++ b/services/customerdb/run/config.toml @@ -0,0 +1,89 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "23h" +DBName = "cyclops" +Host = "localhost" +Password = "pass1234" +Port = 5432 +# SSLMode = enable | disable +SSLMode = "disable" +UserName = "cyclops" + +[EVENTS] +Filters = [ "filter1", "filter2" ] + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +# "" for no file-logging +LogFile = "" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8000" +CDR = "cdr:8000" +CreditManager = "creditsystem:8000" +CustomerDB = "customerdb:8000" +EventsEngine = "eventsengine:8000" +PlanManager = "planmanager:8000" +UDR = "udr:8000" + +[KAFKA] +Brokers = [ "kafka1:9092", "kafka2:9092", "kafka3:9092" ] +CDRIn = [ "CDR" ] +CDROut = [ "Credit" ] +Credit-SystemIn = [ "Credit" ] +EventsEngineIn = [ "Events" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMin = 10e3 +SizeMax = 10e6 +UDRIn = [ "UDR" ] +UDROut = [ "CDR" ] + +[PLANS] +Default = "-1" +Education = "-2" + +[PROMETHEUS] +Host = "prometheus:9090" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + diff --git a/services/customerdb/run/docker-compose.yml b/services/customerdb/run/docker-compose.yml new file mode 100644 index 0000000..8a6e52e --- /dev/null +++ b/services/customerdb/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: SERVICE:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/services/customerdb/run/key.key b/services/customerdb/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/customerdb/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/customerdb/server/config.go b/services/customerdb/server/config.go new file mode 100644 index 0000000..4eb0cf9 --- /dev/null +++ b/services/customerdb/server/config.go @@ -0,0 +1,223 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + DefaultPlans map[string]string + Prometheus prometheusConfig +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type planConfig struct { + Default string +} +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("database.cacheretention"), + DbName: viper.GetString("database.dbname"), + Host: viper.GetString("database.host"), + Password: viper.GetString("database.password"), + Port: viper.GetInt("database.port"), + SSLMode: viper.GetString("database.sslmode"), + Username: viper.GetString("database.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + DefaultPlans: viper.GetStringMapString("plans"), + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/services/customerdb/server/customerManager/customerManager.go b/services/customerdb/server/customerManager/customerManager.go new file mode 100644 index 0000000..79ebf33 --- /dev/null +++ b/services/customerdb/server/customerManager/customerManager.go @@ -0,0 +1,289 @@ +package customerManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/customer_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// CustomerManager is the struct defined to group and contain all the methods +// that interact with the customer endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +// - BasePath: a string with the base path of the system. +type CustomerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager + BasePath string +} + +// New is the function to create the struct CustomerManager that grant +// access to the methods to interact with the customer endpoint. +// Parameters: +// - db: a reference to the DbParameter to be able to interact with the db methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// - bp: a string containing the base path of the service. +// Returns: +// - CustomerManager: struct to interact with customer endpoint functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *CustomerManager { + + l.Trace.Printf("[CustomerManager] Generating new CustomerManager.\n") + + monit.InitEndpoint("customer") + + return &CustomerManager{ + db: db, + monit: monit, + BasePath: bp, + } + +} + +// AddCustomer (Swagger func) is the function behind the (POST) API Endpoint +// /customer +// Its function is to add the provided customer into the db. +func (m *CustomerManager) AddCustomer(ctx context.Context, params customer_management.AddCustomerParams) middleware.Responder { + + l.Trace.Printf("[CustomerManager] AddCustomer endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("customer", callTime) + + id, customerStatus, productStatus := m.db.AddCustomer(params.Customer) + + switch customerStatus { + + case statusOK: + + if productStatus == statusOK { + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Customer added to the system", + APILink: m.BasePath + "/customer/" + id, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/customer"}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewAddCustomerCreated().WithPayload(&acceptedReturn) + + } + + case statusFail: + + s := "It wasn't possible to insert the Customer in the system." + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/customer"}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewAddCustomerInternalServerError().WithPayload(&errorReturn) + + case statusDuplicated: + + s := "The Customer already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/customer"}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewAddCustomerConflict().WithPayload(&conflictReturn) + + } + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Customer added to the system. There might have been problems when adding asociated products", + APILink: m.BasePath + "/customer/" + id, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "POST", "route": "/customer"}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewAddCustomerAccepted().WithPayload(&acceptedReturn) + +} + +// GetCustomer (Swagger func) is the function behind the (GET) API Endpoint +// /customer/{id} +// Its function is to retrieve the information that the system has about the +// customer whose ID has been provided. +func (m *CustomerManager) GetCustomer(ctx context.Context, params customer_management.GetCustomerParams) middleware.Responder { + + l.Trace.Printf("[CustomerManager] GetCustomer endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("customer", callTime) + + customer, e := m.db.GetCustomer(params.ID, m.BasePath) + + if e != nil { + + s := "There was an error retrieving the Customer from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/customer/" + params.ID}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewGetCustomerInternalServerError().WithPayload(&errorReturn) + + } + + if customer != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/customer/" + params.ID}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewGetCustomerOK().WithPayload(customer) + + } + + s := "The Customer doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/customer/" + params.ID}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewGetCustomerNotFound().WithPayload(&missingReturn) + +} + +// ListCustomers (Swagger func) is the function behind the (GET) API Endpoint +// /customer +// Its function is to provide a list containing all the customers in the system. +func (m *CustomerManager) ListCustomers(ctx context.Context, params customer_management.ListCustomersParams) middleware.Responder { + + l.Trace.Printf("[CustomerManager] ListCustomers endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("customer", callTime) + + customers, e := m.db.ListCustomers() + + if e != nil { + + s := "There was an error retrieving the Customers from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/customer"}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewListCustomersInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/customer"}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewListCustomersOK().WithPayload(customers) + +} + +// UpdateCustomer (Swagger func) is the function behind the (PUT) API Endpoint +// /customer/{id} +// Its function is to update the customer whose ID is provided with the new data. +func (m *CustomerManager) UpdateCustomer(ctx context.Context, params customer_management.UpdateCustomerParams) middleware.Responder { + + l.Trace.Printf("[CustomerManager] UpdateCustomer endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("customer", callTime) + + customer := params.Customer + customer.CustomerID = params.ID + + customerStatus, productStatus := m.db.UpdateCustomer(customer) + + switch customerStatus { + + case statusOK: + + if productStatus == statusOK { + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Customer updated in the system", + APILink: m.BasePath + "/customer/" + params.Customer.CustomerID, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/customer/" + params.ID}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewUpdateCustomerOK().WithPayload(&acceptedReturn) + + } + + case statusFail: + + s := "It wasn't possible to update the Customer in the system." + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/customer/" + params.ID}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewUpdateCustomerInternalServerError().WithPayload(&errorReturn) + + case statusMissing: + + s := "The Customer doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/customer/" + params.ID}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewUpdateCustomerNotFound().WithPayload(&missingReturn) + + } + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Customer updated in the system. There might have been problems when updating asociated products", + APILink: m.BasePath + "/customer/" + params.Customer.CustomerID, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "PUT", "route": "/customer/" + params.ID}).Inc() + + m.monit.APIHitDone("customer", callTime) + + return customer_management.NewUpdateCustomerAccepted().WithPayload(&acceptedReturn) + +} diff --git a/services/customerdb/server/dbManager/dbManager.go b/services/customerdb/server/dbManager/dbManager.go new file mode 100644 index 0000000..0b8fb46 --- /dev/null +++ b/services/customerdb/server/dbManager/dbManager.go @@ -0,0 +1,681 @@ +package dbManager + +import ( + "errors" + + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// On it there is the following parameters: +// - connStr: strings with the connection information to the database +// - Db: a gorm.DB pointer to the db to invoke all the db methods +type DbParameter struct { + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec +} + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization +// Returns: +// - DbParameter: struct to interact with dbManager functionalities +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + panic(err) + + } + + l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + dp.Db.AutoMigrate(tables...) + + //l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + //dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NewScope(&models.TABLE).TableName() + "', 'TIMESCALE-ROW-INDEX');") + + return &dp + +} + +// ListResellers function extracts from the db all the resellers in the system. +// It only list the resellers, not their linked customers neither the linked +// products to each customer. +// Returns: +// - r: slice of the reseller model with all the resellers in the system. +func (d *DbParameter) ListResellers() (r []*models.Reseller, e error) { + + l.Trace.Printf("[DB] Attempting to fetch reseller list now.\n") + + if e = d.Db.Find(&r).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] resellers in the db.\n", len(r)) + + return + +} + +// ListCustomers function extracts from the db all the customers in the system. +// It only list the customerss, not their linked products. +// Returns: +// - c: slice of the customers model with all the customers in the system. +func (d *DbParameter) ListCustomers() (c []*models.Customer, e error) { + + l.Trace.Printf("[DB] Attempting to fetch customers list now.\n") + + if e = d.Db.Find(&c).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] customers in the db.\n", len(c)) + + return + +} + +// ListProducts function extracts from the db all the products in the system. +// Returns: +// - p: slice of the products model with all the products in the system. +func (d *DbParameter) ListProducts() (p []*models.Product, e error) { + + l.Trace.Printf("[DB] Attempting to fetch products list now.\n") + + if e = d.Db.Find(&p).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] products in the db.\n", len(p)) + + return + +} + +// GetReseller function extracts from the db the information that the system +// has about the specified reseller. +// Internally this function makes use of GetCustomers() to fill the information +// about all the customers linked to the specified reseller. +// Parameters: +// - id: string containing the id of the reseller to be gotten. +// - host: string containing the basepath of the server for filling out the APILink +// field of the linked customers and products. +// Returns: +// - A reference to the reseller's model containing all the information in the +// system linked to the specified reseller. +func (d *DbParameter) GetReseller(id string, host string) (*models.Reseller, error) { + + l.Trace.Printf("[DB] Attempting to get reseller [ %v ] now.\n", id) + + var r models.Reseller + + e := d.Db.Where(&models.Reseller{ResellerID: id}).First(&r).Error + + if errors.Is(e, gorm.ErrRecordNotFound) { + + l.Warning.Printf("[DB] Unable to fetch existing record for reseller [ %v ], check with administrator.\n", id) + + } else { + + l.Info.Printf("[DB] Found existing record for reseller [ %v ] successfully.\n", r.Name) + + r.Customers = d.GetCustomers(id, host) + + } + + return &r, e + +} + +// GetCustomer function extracts from the db the information that the system +// has about the specified customer. +// Internally this function makes use of GetProducts() to fill the information +// about all the products linked to the specified customer. +// Parameters: +// - id: string containing the id of the customer to be gotten. +// - host: string containing the basepath of the server for filling out the APILink +// field of the linked products. +// Returns: +// - A reference to the customer's model containing all the information in the +// system linked to the specified customer. +func (d *DbParameter) GetCustomer(id string, host string) (*models.Customer, error) { + + l.Trace.Printf("[DB] Attempting to get customer [ %v ] now.\n", id) + + var c models.Customer + + e := d.Db.Where(&models.Customer{CustomerID: id}).First(&c).Error + + if errors.Is(e, gorm.ErrRecordNotFound) { + + l.Warning.Printf("[DB] Unable to fetch existing record for customer [ %v ], check with administrator.\n", id) + + } else { + + l.Info.Printf("[DB] Found existing record for customer [ %v ] successfully.\n", c.Name) + + c.Products = d.GetProducts(id, host) + + } + + return &c, e + +} + +// GetProduct function extracts from the db the information that the system +// has about the specified product. +// Parameters: +// - id: string containing the id of the product to be gotten. +// Returns: +// - A reference to the product's model containing all the information in the +// system linked to the specified product. +func (d *DbParameter) GetProduct(id string) (*models.Product, error) { + + l.Trace.Printf("[DB] Attempting to get product [ %v ] now.\n", id) + + var p models.Product + + e := d.Db.Where(&models.Product{ProductID: id}).First(&p).Error + + if errors.Is(e, gorm.ErrRecordNotFound) { + + l.Warning.Printf("[DB] Unable to fetch existing record for product [ %v ], check with administrator.\n", id) + + } else { + + l.Info.Printf("[DB] Found existing record for product [ %v ] successfully.\n", p.Name) + + } + + return &p, e + +} + +// GetCustomers function extracts from the db the information that the system +// has about all the customers linked to the specified reseller id. +// Internally this function makes use of GetProducts() to fill the information +// about all the products linked to each customer. +// Parameters: +// - id: string containing the id of the customer to be gotten. +// - host: string containing the basepath of the server for filling out the APILink +// field of the customers and the linked products. +// Returns: +// - A slice of the customer's model containing all the information in the +// system linked to the specified reseller id. +func (d *DbParameter) GetCustomers(id string, host string) (c []*models.Customer) { + + l.Trace.Printf("[DB] Attempting to fetch customers for reseller [ %v ] now.\n", id) + + var custs, customers []models.Customer + + if e := d.Db.Where(&models.Customer{ResellerID: id}).Find(&customers).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation while retrieving linked custommers. Error: %v\n", e) + + } + + for _, customer := range customers { + + customer.Products = d.GetProducts(customer.CustomerID, host) + customer.APILink = host + "/customer/" + customer.CustomerID + + custs = append(custs, customer) + + } + + //This is the only way to avoid the issue with the unproper assigning of + //&Elemnt when using range over and array + for id := range custs { + + c = append(c, &custs[id]) + + } + + l.Trace.Printf("[DB] Found [ %d ] customers for reseller [ %v ].\n", len(c), id) + + return + +} + +// GetProducts function extracts from the db the information that the system +// has about all the products linked to the specified customer id. +// Parameters: +// - id: string containing the id of the customer to be gotten. +// - host: string containing the basepath of the server for filling out the APILink +// field of products. +// Returns: +// - A slice of the product's model containing all the information in the +// system linked to the specified customer id. +func (d *DbParameter) GetProducts(id string, host string) (p []*models.Product) { + + l.Trace.Printf("[DB] Attempting to fetch products for customer [ %v ] now.\n", id) + + var products []models.Product + + if e := d.Db.Where(&models.Product{CustomerID: id}).Find(&products).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation while retrieving linked products. Error: %v\n", e) + + } + + for i := range products { + + product := products[i] + + product.APILink = host + "/product/" + product.ProductID + + p = append(p, &product) + + } + + l.Trace.Printf("[DB] Found [ %d ] products for customer [ %v ].\n", len(p), id) + + return + +} + +// AddReseller function inserts the reseller and its linked customers and products +// into the system. +// Since the system is designed to not raised a problem when it fails to add new +// items in the db, the method constains a basic feedback control to know if +// there was a problem when inserting the reseller or any of its linked +// components in the db. +// Parameters: +// - r: reseller's model containing the information to be imported in the db. +// Returns: +// - rs: integer with the state of adding the reseller itself. +// - cs: integer with the state of adding the linked customers. +// - ps: integer with the state of adding the linked products. +func (d *DbParameter) AddReseller(r *models.Reseller) (id string, rs int, cs int, ps int) { + + l.Trace.Printf("[DB] Attempting to add reseller [ %v ] now.\n", r.ResellerID) + + var r0 models.Reseller + + if e := d.Db.Where(r).First(&r0).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + if e := d.Db.Create(r); e.Error == nil { + + l.Info.Printf("[DB] Inserted new record for reseller [ %v ] successfully.\n", r.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Resellers added"}).Inc() + + rs, cs, ps = statusOK, statusOK, statusOK + + id = (*e.Statement.Model.(*models.Reseller)).ResellerID + + for _, c := range r.Customers { + + c.ResellerID = id + + _, a, b := d.AddCustomer(c) + + if a != statusOK { + + cs = statusFail + + } + + if b != statusOK { + + ps = statusFail + + } + + } + + } else { + + l.Warning.Printf("[DB] Unable to insert the record for reseller [ %v ], check with administrator.\n", r.Name) + + rs = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for reseller [ %v ] already exists, check with administrator.\n", r.Name) + + rs = statusDuplicated + + } + + return + +} + +// AddCustomer function inserts the customer and its linked products into the system. +// Since the system is designed to not raised a problem when it fails to add new +// items in the db, the method constains a basic feedback control to know if +// there was a problem when inserting the customer or any of its linked +// components in the db. +// Parameters: +// - c: customer's model containing the information to be imported in the db. +// Returns: +// - cs: integer with the state of adding the customer itself. +// - ps: integer with the state of adding the linked products. +func (d *DbParameter) AddCustomer(c *models.Customer) (id string, cs int, ps int) { + + l.Trace.Printf("[DB] Attempting to add customer [ %v ] now.\n", c.CustomerID) + + var c0 models.Customer + + if e := d.Db.Where(c).First(&c0).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + if e := d.Db.Create(c); e.Error == nil { + + l.Info.Printf("[DB] Inserted new record for customer [ %v ] successfully.\n", c.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Customers added"}).Inc() + + cs, ps = statusOK, statusOK + + id = (*e.Statement.Model.(*models.Customer)).CustomerID + + for _, p := range c.Products { + + p.CustomerID = id + + _, a := d.AddProduct(p) + + if a != statusOK { + + ps = statusFail + + } + + } + + } else { + + l.Warning.Printf("[DB] Unable to insert the record for customer [ %v ], check with administrator.\n", c.Name) + + cs = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for customer [ %v ] already exists, check with administrator.\n", c.Name) + + cs = statusDuplicated + + } + + return + +} + +// AddProduct function inserts the product into the system. +// Since the system is designed to not raised a problem when it fails to add new +// items in the db, the method constains a basic feedback control to know if +// there was a problem when inserting the product in the db. +// Parameters: +// - p: product's model containing the information to be imported in the db. +// Returns: +// - ps: integer with the state of adding the product. +func (d *DbParameter) AddProduct(p *models.Product) (id string, ps int) { + + l.Trace.Printf("[DB] Attempting to add product [ %v ] now.\n", p.ProductID) + + var p0 models.Product + + if e := d.Db.Where(p).First(&p0).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + if e := d.Db.Create(p); e.Error == nil { + + l.Info.Printf("[DB] Inserted new record for prolduct [ %v ] successfully.\n", p.Name) + + id = (*e.Statement.Model.(*models.Product)).ProductID + + d.Metrics["count"].With(prometheus.Labels{"type": "Products added"}).Inc() + + ps = statusOK + + } else { + + l.Warning.Printf("[DB] Unable to insert the record for product [ %v ], check with administrator.\n", p.Name) + + ps = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for product [ %v ] already exists, check with administrator.\n", p.Name) + + ps = statusDuplicated + + } + + return + +} + +// UpdateReseller function inserts the updated reseller information and its +// linked customers and products into the system, creating new ones in case of +// no previous version found in the database. +// Since the system is designed to not raised a problem when it fails to add new +// items in the db, the method constains a basic feedback control to know if +// there was a problem when inserting the updated reseller or any of its linked +// components in the db. +// Parameters: +// - r: reseller's model containing the information to be imported in the db. +// Returns: +// - rs: integer with the state of updating the reseller itself. +// - cs: integer with the state of updating the linked customers. +// - ps: integer with the state of updating the linked products. +func (d *DbParameter) UpdateReseller(r *models.Reseller) (rs int, cs int, ps int) { + + l.Trace.Printf("[DB] Attempting to update reseller [ %v ] now.\n", r.ResellerID) + + var r0 models.Reseller + + if e := d.Db.Where(models.Reseller{ResellerID: r.ResellerID}).First(&r0).Error; !errors.Is(e, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&r0).Updates(*r).Error; e == nil { + + l.Info.Printf("[DB] Updated record for reseller [ %v ] successfully.\n", r.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Resellers updated"}).Inc() + + rs, cs, ps = statusOK, statusOK, statusOK + + for _, c := range r.Customers { + + c.ResellerID = r.ResellerID + + if a, _ := d.UpdateCustomer(c); a != statusOK { + + l.Trace.Printf("[DB] Attempt to update customer [ %v ] failed, considering it as new customer to be added.\n", c.CustomerID) + + _, b, d := d.AddCustomer(c) + + if b != statusOK { + + l.Trace.Printf("[DB] Attempt to add customer [ %v ] failed.\n", c.CustomerID) + + cs = statusFail + + } + + if d != statusOK { + + ps = statusFail + + } + + } + } + + } else { + + l.Warning.Printf("[DB] Unable to update record for reseller [ %v ], check with administrator.\n", r.Name) + + rs = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for reseller [ %v ] not found, check with administrator.\n", r.Name) + + rs = statusMissing + + } + + return + +} + +// UpdateCustomer function inserts the updated customer information and its +// linked products into the system, creating new ones in case of no previous +// version found in the database. +// Since the system is designed to not raised a problem when it fails to add new +// items in the db, the method constains a basic feedback control to know if +// there was a problem when inserting the updated customer or any of its linked +// components in the db. +// Parameters: +// - c: customer's model containing the information to be imported in the db. +// Returns: +// - cs: integer with the state of updating the customer itself. +// - ps: integer with the state of updating the linked products. +func (d *DbParameter) UpdateCustomer(c *models.Customer) (cs int, ps int) { + + l.Trace.Printf("[DB] Attempting to update customer [ %v ] now.\n", c.CustomerID) + + var c0 models.Customer + + if e := d.Db.Where(&models.Customer{CustomerID: c.CustomerID}).First(&c0).Error; !errors.Is(e, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&c0).Updates(*c).Error; e == nil { + + l.Info.Printf("[DB] Updated record for customer [ %v ] successfully.\n", c.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Customers updated"}).Inc() + + cs, ps = statusOK, statusOK + + for _, p := range c.Products { + + p.CustomerID = c.CustomerID + + if d.UpdateProduct(p) != statusOK { + + l.Trace.Printf("[DB] Attempt to update product [ %v ] failed, considering it as new product to be added.\n", p.ProductID) + + _, a := d.AddProduct(p) + + if a != statusOK { + + l.Trace.Printf("[DB] Attempt to add product [ %v ] failed.\n", p.ProductID) + + cs = statusFail + + } + + } + + } + + } else { + + l.Warning.Printf("[DB] Unable to update record for customer [ %v ], check with administrator.\n", c.Name) + + cs = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for customer [ %v ] not found, check with administrator.\n", c.Name) + + cs = statusMissing + + } + + return + +} + +// UpdateProduct function inserts the updated product information in the system. +// Since the system is designed to not raised a problem when it fails to add new +// items in the db, the method constains a basic feedback control to know if +// there was a problem when inserting the updated product in the db. +// Parameters: +// - p: product's model containing the information to be imported in the db. +// Returns: +// - ps: integer with the state of updating the product. +func (d *DbParameter) UpdateProduct(p *models.Product) (ps int) { + + l.Trace.Printf("[DB] Attempting to update product [ %v ] now.\n", p.ProductID) + + var p0 models.Product + + if e := d.Db.Where(&models.Product{ProductID: p.ProductID}).First(&p0).Error; !errors.Is(e, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&p0).Updates(*p).Error; e == nil { + + l.Info.Printf("[DB] Updated record for product [ %v ] successfully.\n", p.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Products updated"}).Inc() + + ps = statusOK + + } else { + + l.Warning.Printf("[DB] Unable to update record for product [ %v ], check with administrator.\n", p.Name) + + ps = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for product [ %v ] not found, check with administrator.\n", p.Name) + + ps = statusMissing + + } + + return + +} diff --git a/services/customerdb/server/main.go b/services/customerdb/server/main.go new file mode 100644 index 0000000..7731828 --- /dev/null +++ b/services/customerdb/server/main.go @@ -0,0 +1,176 @@ +package main + +import ( + "crypto/tls" + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/services/customerdb/server/metrics.go b/services/customerdb/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/services/customerdb/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/services/customerdb/server/productManager/productManager.go b/services/customerdb/server/productManager/productManager.go new file mode 100644 index 0000000..42d502f --- /dev/null +++ b/services/customerdb/server/productManager/productManager.go @@ -0,0 +1,253 @@ +package productManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/product_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// ProductManager is the struct defined to group and contain all the methods +// that interact with the product endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +// - BasePath: a string with the base path of the system. +type ProductManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager + BasePath string +} + +// New is the function to create the struct ProductManager that grant +// access to the methods to interact with the Product endpoint. +// Parameters: +// - db: a reference to the DbParameter to be able to interact with the db methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// - bp: a string containing the base path of the service. +// Returns: +// - ProductManager: struct to interact with product endpoint functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *ProductManager { + + l.Trace.Printf("[ProductManager] Generating new ProductManager.\n") + + monit.InitEndpoint("product") + + return &ProductManager{ + db: db, + monit: monit, + BasePath: bp, + } + +} + +// AddProduct (Swagger func) is the function behind the (POST) API Endpoint +// /product +// Its function is to add the provided product into the db. +func (m *ProductManager) AddProduct(ctx context.Context, params product_management.AddProductParams) middleware.Responder { + + l.Trace.Printf("[ProductManager] AddProduct endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("product", callTime) + + id, productStatus := m.db.AddProduct(params.Product) + + switch productStatus { + + case statusOK: + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Product added to the system", + APILink: m.BasePath + "/product/" + id, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/product"}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewAddProductCreated().WithPayload(&acceptedReturn) + + case statusFail: + + s := "It wasn't possible to insert the Product in the system." + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/product"}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewAddProductInternalServerError().WithPayload(&errorReturn) + + } + + s := "The Product already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/product"}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewAddProductConflict().WithPayload(&conflictReturn) + +} + +// GetProduct (Swagger func) is the function behind the (GET) API Endpoint +// /product/{id} +// Its function is to retrieve the information that the system has about the +// product whose ID has been provided. +func (m *ProductManager) GetProduct(ctx context.Context, params product_management.GetProductParams) middleware.Responder { + + l.Trace.Printf("[ProductManager] GetProduct endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("product", callTime) + + product, e := m.db.GetProduct(params.ID) + + if e != nil { + + s := "There was an error retrieving the Product from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/product/" + params.ID}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewGetProductInternalServerError().WithPayload(&errorReturn) + + } + + if product != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/product/" + params.ID}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewGetProductOK().WithPayload(product) + + } + + s := "The Product doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/product/" + params.ID}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewGetProductNotFound().WithPayload(&missingReturn) + +} + +// ListProducts (Swagger func) is the function behind the (GET) API Endpoint +// /product +// Its function is to provide a list containing all the products in the system. +func (m *ProductManager) ListProducts(ctx context.Context, params product_management.ListProductsParams) middleware.Responder { + + l.Trace.Printf("[ProductManager] ListProducts endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("product", callTime) + + products, e := m.db.ListProducts() + + if e != nil { + + s := "There was an error retrieving the Products from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/product"}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewListProductsInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/product"}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewListProductsOK().WithPayload(products) + +} + +// UpdateProduct (Swagger func) is the function behind the (PUT) API Endpoint +// /product/{id} +// Its function is to update the product whose ID is provided with the new data. +func (m *ProductManager) UpdateProduct(ctx context.Context, params product_management.UpdateProductParams) middleware.Responder { + + l.Trace.Printf("[ProductManager] UpdateProduct endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("product", callTime) + + product := params.Product + product.ProductID = params.ID + + switch productStatus := m.db.UpdateProduct(product); productStatus { + + case statusOK: + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Product updated in the system", + APILink: m.BasePath + "/product/" + params.Product.ProductID, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/product/" + params.ID}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewUpdateProductOK().WithPayload(&acceptedReturn) + + case statusFail: + + s := "It wasn't possible to update the product in the system." + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/product/" + params.ID}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewUpdateProductInternalServerError().WithPayload(&errorReturn) + + } + + s := "The Product doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/product/" + params.ID}).Inc() + + m.monit.APIHitDone("product", callTime) + + return product_management.NewUpdateProductNotFound().WithPayload(&missingReturn) + +} diff --git a/services/customerdb/server/resellerManager/resellerManager.go b/services/customerdb/server/resellerManager/resellerManager.go new file mode 100644 index 0000000..1bfd363 --- /dev/null +++ b/services/customerdb/server/resellerManager/resellerManager.go @@ -0,0 +1,289 @@ +package resellerManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/reseller_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// ResellerManager is the struct defined to group and contain all the methods +// that interact with the reseller endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +// - BasePath: a string with the base path of the system. +type ResellerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager + BasePath string +} + +// New is the function to create the struct ResellerManager that grant +// access to the methods to interact with the reseller endpoint. +// Parameters: +// - db: a reference to the DbParameter to be able to interact with the db methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// - bp: a string containing the base path of the service. +// Returns: +// - ResellerManager: struct to interact with the reseller endpoint functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *ResellerManager { + + l.Trace.Printf("[ResellerManager] Generating new ResellerManager.\n") + + monit.InitEndpoint("reseller") + + return &ResellerManager{ + db: db, + monit: monit, + BasePath: bp, + } + +} + +// AddReseller (Swagger func) is the function behind the (POST) API Endpoint +// /reseller +// Its function is to add the provided reseller into the db. +func (m *ResellerManager) AddReseller(ctx context.Context, params reseller_management.AddResellerParams) middleware.Responder { + + l.Trace.Printf("[ResellerManager] AddReseller endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("reseller", callTime) + + id, resellerStatus, customerStatus, productStatus := m.db.AddReseller(params.Reseller) + + switch resellerStatus { + + case statusOK: + + if customerStatus == statusOK && productStatus == statusOK { + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Reseller added to the system", + APILink: m.BasePath + "/reseller/" + id, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/reseller"}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewAddResellerCreated().WithPayload(&acceptedReturn) + + } + + case statusFail: + + s := "It wasn't possible to insert the Reseller in the system." + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/reseller"}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewAddResellerInternalServerError().WithPayload(&errorReturn) + + case statusDuplicated: + + s := "The Reseller already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/reseller"}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewAddResellerConflict().WithPayload(&conflictReturn) + + } + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Reseller added to the system. There might have been problems when adding asociated resellers and/or products", + APILink: m.BasePath + "/reseller/" + id, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "POST", "route": "/reseller"}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewAddResellerAccepted().WithPayload(&acceptedReturn) + +} + +// GetReseller (Swagger func) is the function behind the (GET) API Endpoint +// /reseller/{id} +// Its function is to retrieve the information that the system has about the +// reseller whose ID has been provided. +func (m *ResellerManager) GetReseller(ctx context.Context, params reseller_management.GetResellerParams) middleware.Responder { + + l.Trace.Printf("[ResellerManager] GetReseller endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("reseller", callTime) + + reseller, e := m.db.GetReseller(params.ID, m.BasePath) + + if e != nil { + + s := "There was an error retrieving the Reseller from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/reseller/" + params.ID}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewGetResellerInternalServerError().WithPayload(&errorReturn) + + } + + if reseller != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/reseller/" + params.ID}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewGetResellerOK().WithPayload(reseller) + + } + + s := "The Reseller doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/reseller/" + params.ID}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewGetResellerNotFound().WithPayload(&missingReturn) + +} + +// ListResellers (Swagger func) is the function behind the (GET) API Endpoint +// /reseller +// Its function is to provide a list containing all the resellers in the system. +func (m *ResellerManager) ListResellers(ctx context.Context, params reseller_management.ListResellersParams) middleware.Responder { + + l.Trace.Printf("[ResellerManager] ListResellers endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("reseller", callTime) + + resellers, e := m.db.ListResellers() + + if e != nil { + + s := "There was an error retrieving the Resellers from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/reseller"}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewListResellersInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/reseller"}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewListResellersOK().WithPayload(resellers) + +} + +// UpdateReseller (Swagger func) is the function behind the (PUT) API Endpoint +// /reseller/{id} +// Its function is to update the reseller whose ID is provided with the new data. +func (m *ResellerManager) UpdateReseller(ctx context.Context, params reseller_management.UpdateResellerParams) middleware.Responder { + + l.Trace.Printf("[ResellerManager] UpdateReseller endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("reseller", callTime) + + reseller := params.Reseller + reseller.ResellerID = params.ID + + resellerStatus, customerStatus, productStatus := m.db.UpdateReseller(reseller) + + switch resellerStatus { + + case statusOK: + + if customerStatus == statusOK && productStatus == statusOK { + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Reseller updated in the system", + APILink: m.BasePath + "/reseller/" + params.Reseller.ResellerID, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/reseller/" + params.ID}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewUpdateResellerOK().WithPayload(&acceptedReturn) + + } + + case statusFail: + + s := "It wasn't possible to update the Reseller in the system." + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/reseller/" + params.ID}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewUpdateResellerInternalServerError().WithPayload(&errorReturn) + + case statusMissing: + + s := "The Reseller doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/reseller/" + params.ID}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewUpdateResellerNotFound().WithPayload(&missingReturn) + + } + + acceptedReturn := models.ItemCreatedResponse{ + Message: "Reseller updated in the system. There might have been problems when updating asociated resellers and/or products", + APILink: m.BasePath + "/reseller/" + params.Reseller.ResellerID, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "202", "method": "PUT", "route": "/reseller/" + params.ID}).Inc() + + m.monit.APIHitDone("reseller", callTime) + + return reseller_management.NewUpdateResellerAccepted().WithPayload(&acceptedReturn) + +} diff --git a/services/customerdb/server/security.go b/services/customerdb/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/services/customerdb/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/services/customerdb/server/service.go b/services/customerdb/server/service.go new file mode 100644 index 0000000..6cc1457 --- /dev/null +++ b/services/customerdb/server/service.go @@ -0,0 +1,79 @@ +package main + +import ( + "net/http" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/customerManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/productManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/resellerManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,...,N have to be customized + db := dbStart(&models.Product{}, &models.Customer{}, &models.Reseller{}) + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + bp := getBasePath() + + // Parts of the service HERE + c := customerManager.New(db, mon, bp) + p := productManager.New(db, mon, bp) + r := resellerManager.New(db, mon, bp) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + CustomerManagementAPI: c, + ProductManagementAPI: p, + ResellerManagementAPI: r, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} diff --git a/services/customerdb/server/statusManager/statusManager.go b/services/customerdb/server/statusManager/statusManager.go new file mode 100644 index 0000000..c755b4b --- /dev/null +++ b/services/customerdb/server/statusManager/statusManager.go @@ -0,0 +1,325 @@ +package statusManager + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 + mutex *sync.Mutex +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + mutex = &sync.Mutex{} + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + avgTime[key] = t.UnixNano() + mutex.Unlock() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + previous, exists := avgTime[key] + mutex.Unlock() + + if exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + mutex.Lock() + delete(avgTime, key) + mutex.Unlock() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/services/customerdb/server/triggerManager/triggerManager.go b/services/customerdb/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..1fb4ae1 --- /dev/null +++ b/services/customerdb/server/triggerManager/triggerManager.go @@ -0,0 +1,61 @@ +package triggerManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// TriggerManager is the struct defined to group and contain all the methods +// that interact with the trigger subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type TriggerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct TriggerManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// Returns: +// - TriggerManager: struct to interact with triggerManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *TriggerManager { + + l.Trace.Printf("[Trigger] Generating new triggerManager.\n") + + monit.InitEndpoint("trigger") + + return &TriggerManager{ + db: db, + monit: monit, + } + +} + +// ExecSample (Swagger func) is the function behind the /trigger/sample endpoint. +// It is a dummy function for reference. +func (m *TriggerManager) ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder { + + l.Trace.Printf("[Trigger] ExecSample endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/trigger/sample"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecSampleOK() + +} diff --git a/services/customerdb/swagger.yaml b/services/customerdb/swagger.yaml new file mode 100644 index 0000000..a3d2f3b --- /dev/null +++ b/services/customerdb/swagger.yaml @@ -0,0 +1,1537 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v1.0" +info: + description: An API which supports creation, deletion, listing etc of customers and products + version: "1.0.0" + title: Customer Database Management API + contact: + email: diego@cyclops-labs.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + - name: resellerManagement + description: Actions relating to the management of Resellers + - name: customerManagement + description: Actions relating to the management of Customers + - name: productManagement + description: Actions relating to the management of Products + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - kafka-receiver + - kafka-sender + - status + - trigger + - customer + - product + - reseller + required: true + description: Id of the product to be retrieved + /trigger/sample: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Sample task trigger + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: execSample + responses: + '200': + description: Sample task executed successfully + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + + /customer: + get: + tags: + - customerManagement + produces: + - application/json + summary: List all the customers in the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: listCustomers + responses: + '200': + description: List of customers in the system returned + schema: + type: array + items: + $ref: "#/definitions/Customer" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + post: + tags: + - customerManagement + consumes: + - application/json + produces: + - application/json + summary: Insert a new customer in the system. + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: addCustomer + responses: + '201': + description: New customer was added successfully + schema: + $ref: "#/definitions/ItemCreatedResponse" + '202': + description: The new customer was added but there might have been some fails when adding part of the data + schema: + $ref: "#/definitions/ItemCreatedResponse" + '400': + description: Invalid input, object invalid + '409': + description: The given item already exists + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: customer + in: body + description: Customer to be added + required: true + schema: + $ref: "#/definitions/Customer" + /customer/{id}: + get: + tags: + - customerManagement + produces: + - application/json + summary: Return the information about the customer with the given id + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getCustomer + responses: + '200': + description: Customer with the id given in the system returned + schema: + $ref: "#/definitions/Customer" + '404': + description: The customer with the given id wasn't found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the customer to be retrieved + put: + tags: + - customerManagement + consumes: + - application/json + produces: + - application/json + summary: Updates the information of the customer with the given id + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: updateCustomer + responses: + '200': + description: Customer with the given id was updated + schema: + $ref: "#/definitions/ItemCreatedResponse" + '202': + description: The customer was updated but there might have been some fails when adding part of the data + schema: + $ref: "#/definitions/ItemCreatedResponse" + '404': + description: The customer with the given id wasn't found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the customer to be updated + - name: customer + in: body + description: Customer to be updated + required: true + schema: + $ref: "#/definitions/Customer" + + /product: + get: + tags: + - productManagement + produces: + - application/json + summary: List all the products in the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: listProducts + responses: + '200': + description: List of products in the system returned + schema: + type: array + items: + $ref: "#/definitions/Product" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + post: + tags: + - productManagement + consumes: + - application/json + produces: + - application/json + summary: Insert a new product in the system. + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: addProduct + responses: + '201': + description: New product was added successfully + schema: + $ref: "#/definitions/ItemCreatedResponse" + '400': + description: Invalid input, object invalid + '409': + description: The given item already exists + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: product + in: body + description: Product to be added + required: true + schema: + $ref: "#/definitions/Product" + /product/{id}: + get: + tags: + - productManagement + produces: + - application/json + summary: Return the information about the product with the given id + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getProduct + responses: + '200': + description: Product with the id given in the system returned + schema: + $ref: "#/definitions/Product" + '404': + description: The product with the given id wasn't found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the product to be retrieved + put: + tags: + - productManagement + consumes: + - application/json + produces: + - application/json + summary: Updates the information of the product with the given id + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: updateProduct + responses: + '200': + description: Product with the given id was updated + schema: + $ref: "#/definitions/ItemCreatedResponse" + '404': + description: The product with the given id wasn't found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the product to be updated + - name: product + in: body + description: Product to be updated + required: true + schema: + $ref: "#/definitions/Product" + + /reseller: + get: + tags: + - resellerManagement + produces: + - application/json + summary: List all the resellers in the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: listResellers + responses: + '200': + description: List of resellers in the system returned + schema: + type: array + items: + $ref: "#/definitions/Reseller" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + post: + tags: + - resellerManagement + consumes: + - application/json + produces: + - application/json + summary: Insert a new reseller in the system. + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: addReseller + responses: + '201': + description: New reseller was added successfully + schema: + $ref: "#/definitions/ItemCreatedResponse" + '202': + description: The new reseller was added but there might have been some fails when adding part of the data + schema: + $ref: "#/definitions/ItemCreatedResponse" + '400': + description: Invalid input, object invalid + '409': + description: The given item already exists + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: reseller + in: body + description: Reseller to be added + required: true + schema: + $ref: "#/definitions/Reseller" + /reseller/{id}: + get: + tags: + - resellerManagement + produces: + - application/json + summary: Return the information about the reseller with the given id + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getReseller + responses: + '200': + description: Reseller with the id given in the system returned + schema: + $ref: "#/definitions/Reseller" + '404': + description: The reseller with the given id wasn't found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the reseller to be retrieved + put: + tags: + - resellerManagement + consumes: + - application/json + produces: + - application/json + summary: Updates the information of the reseller with the given id + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: updateReseller + responses: + '200': + description: Reseller with the given id was updated + schema: + $ref: "#/definitions/ItemCreatedResponse" + '202': + description: The reseller was updated but there might have been some fails when adding part of the data + schema: + $ref: "#/definitions/ItemCreatedResponse" + '404': + description: The reseller with the given id wasn't found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + required: true + description: Id of the reseller to be updated + - name: reseller + in: body + description: Reseller to be updated + required: true + schema: + $ref: "#/definitions/Reseller" + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + ItemCreatedResponse: + properties: + Message: + type: string + ApiLink: + type: string + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + + Customer: + type: object + properties: + AbacusCode: + type: string + x-go-custom-tag: gorm:"default:''" + Address: + type: string + ApiLink: + type: string + x-go-custom-tag: gorm:"-" + Billable: + type: boolean + x-go-custom-tag: gorm:"default:true" + default: true + BillContact: + type: string + x-go-custom-tag: gorm:"default:''" + BillCurrency: + type: string + x-go-custom-tag: gorm:"default:CHF" + description: ISO-4217 currency code + default: CHF + enum: + - AED + - AFN + - ALL + - AMD + - ANG + - AOA + - ARS + - AUD + - AWG + - AZN + - BAM + - BBD + - BDT + - BGN + - BHD + - BIF + - BMD + - BND + - BOB + - BOV + - BRL + - BSD + - BTN + - BWP + - BYN + - BZD + - CAD + - CDF + - CHE + - CHF + - CHW + - CLF + - CLP + - CNY + - COP + - COU + - CRC + - CUC + - CUP + - CVE + - CZK + - DJF + - DKK + - DOP + - DZD + - EGP + - ERN + - ETB + - EUR + - FJD + - FKP + - GBP + - GEL + - GHS + - GIP + - GMD + - GNF + - GTQ + - GYD + - HKD + - HNL + - HRK + - HTG + - HUF + - IDR + - ILS + - INR + - IQD + - IRR + - ISK + - JMD + - JOD + - JPY + - KES + - KGS + - KHR + - KMF + - KPW + - KRW + - KWD + - KYD + - KZT + - LAK + - LBP + - LKR + - LRD + - LSL + - LYD + - MAD + - MDL + - MGA + - MKD + - MMK + - MNT + - MOP + - MRU + - MUR + - MVR + - MWK + - MXN + - MXV + - MYR + - MZN + - NAD + - NGN + - NIO + - NOK + - NPR + - NZD + - OMR + - PAB + - PEN + - PGK + - PHP + - PKR + - PLN + - PYG + - QAR + - RON + - RSD + - RUB + - RWF + - SAR + - SBD + - SCR + - SDG + - SEK + - SGD + - SHP + - SLL + - SOS + - SRD + - SSP + - STN + - SVC + - SYP + - SZL + - THB + - TJS + - TMT + - TND + - TOP + - TRY + - TTD + - TWD + - TZS + - UAH + - UGX + - USD + - USN + - UYI + - UYU + - UYW + - UZS + - VES + - VND + - VUV + - WST + - XAF + - XAG + - XAU + - XBA + - XBB + - XBC + - XBD + - XCD + - XDR + - XOF + - XPD + - XPF + - XPT + - XSU + - XTS + - XUA + - XXX + - YER + - ZAR + - ZMW + - ZWL + BillingCode: + type: string + x-go-custom-tag: gorm:"default:''" + BillPeriod: + type: string + x-go-custom-tag: gorm:"default:monthly" + default: monthly + enum: + - daily + - weekly + - bi-weekly + - monthly + - bi-monthly + - quarterly + - semi-annually + - annually + CancelDate: + type: string + x-go-custom-tag: gorm:"type:date;default:2100-12-31" + format: date + ContractEnd: + type: string + x-go-custom-tag: gorm:"type:date;default:2030-12-31" + format: date + ContractStart: + type: string + x-go-custom-tag: gorm:"type:date;default:2019-01-01" + format: date + CustomerId: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + DeletedAt: + type: string + x-go-custom-tag: gorm:"type:timestamptz" + x-nullable: true + format: datetime + Discount: + type: number + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + format: double + default: 0.0 + EmailBcc: + type: string + x-go-custom-tag: gorm:"default:''" + format: email + EmailCc: + type: string + x-go-custom-tag: gorm:"default:''" + format: email + EmailTo: + type: string + x-go-custom-tag: gorm:"default:''" + format: email + InvoiceMode: + type: string + x-go-custom-tag: gorm:"default:email" + default: email + enum: + - email + - post + IsActive: + type: boolean + x-go-custom-tag: gorm:"default:true" + default: true + Language: + type: string + x-go-custom-tag: gorm:"default:DE" + description: ISO-369-1 alpha-2 language codes + default: DE + enum: + - AA + - AB + - AE + - AF + - AK + - AM + - AN + - AR + - AS + - AV + - AY + - AZ + - BA + - BE + - BG + - BH + - BI + - BM + - BN + - BO + - BR + - BS + - CA + - CE + - CH + - CO + - CR + - CS + - CU + - CV + - CY + - DA + - DE + - DV + - DZ + - EE + - EL + - EN + - EO + - ES + - ET + - EU + - FA + - FF + - FI + - FJ + - FO + - FR + - FY + - GA + - GD + - GL + - GN + - GU + - GV + - HA + - HE + - HI + - HO + - HR + - HT + - HU + - HY + - HZ + - IA + - ID + - IE + - IG + - II + - IK + - IO + - IS + - IT + - IU + - JA + - JV + - KA + - KG + - KI + - KJ + - KK + - KL + - KM + - KN + - KO + - KR + - KS + - KU + - KV + - KW + - KY + - LA + - LB + - LG + - LI + - LN + - LO + - LT + - LU + - LV + - MG + - MH + - MI + - MK + - ML + - MN + - MR + - MS + - MT + - MY + - NA + - NB + - ND + - NE + - NG + - NL + - NN + - "NO" + - NR + - NV + - NY + - OC + - OJ + - OM + - OR + - OS + - PA + - PI + - PL + - PS + - PT + - QU + - RM + - RN + - RO + - RU + - RW + - SA + - SC + - SD + - SE + - SG + - SI + - SK + - SL + - SM + - SN + - SO + - SQ + - SR + - SS + - ST + - SU + - SV + - SW + - TA + - TE + - TG + - TH + - TI + - TK + - TL + - TN + - TO + - TR + - TS + - TT + - TW + - TY + - UG + - UK + - UR + - UZ + - VE + - VI + - VO + - WA + - WO + - XH + - YI + - YO + - ZA + - ZH + - ZU + Name: + type: string + ParentCustomerId: + type: string + PlanId: + type: string + x-go-custom-tag: gorm:"default:'DEFAULT'" + Products: + type: array + x-go-custom-tag: gorm:"-" + items: + $ref: "#/definitions/Product" + ResellerId: + type: string + + Product: + type: object + properties: + ApiLink: + type: string + x-go-custom-tag: gorm:"-" + CancelDate: + type: string + x-go-custom-tag: gorm:"type:date;default:2100-12-31" + format: date + default: 2100-12-31 + CustomerId: + type: string + DeletedAt: + type: string + x-go-custom-tag: gorm:"type:timestamptz" + x-nullable: true + format: datetime + Discount: + type: number + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + format: double + default: 0.0 + Name: + type: string + PlanId: + type: string + x-go-custom-tag: gorm:"default:'DEFAULT'" + ProductId: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + Type: + type: string + + Reseller: + type: object + properties: + AbacusCode: + type: string + x-go-custom-tag: gorm:"default:''" + Address: + type: string + ApiLink: + type: string + x-go-custom-tag: gorm:"-" + Billable: + type: boolean + x-go-custom-tag: gorm:"default:true" + default: true + BillContact: + type: string + x-go-custom-tag: gorm:"default:''" + BillCurrency: + type: string + x-go-custom-tag: gorm:"default:CHF" + description: ISO-4217 currency code + default: CHF + enum: + - AED + - AFN + - ALL + - AMD + - ANG + - AOA + - ARS + - AUD + - AWG + - AZN + - BAM + - BBD + - BDT + - BGN + - BHD + - BIF + - BMD + - BND + - BOB + - BOV + - BRL + - BSD + - BTN + - BWP + - BYN + - BZD + - CAD + - CDF + - CHE + - CHF + - CHW + - CLF + - CLP + - CNY + - COP + - COU + - CRC + - CUC + - CUP + - CVE + - CZK + - DJF + - DKK + - DOP + - DZD + - EGP + - ERN + - ETB + - EUR + - FJD + - FKP + - GBP + - GEL + - GHS + - GIP + - GMD + - GNF + - GTQ + - GYD + - HKD + - HNL + - HRK + - HTG + - HUF + - IDR + - ILS + - INR + - IQD + - IRR + - ISK + - JMD + - JOD + - JPY + - KES + - KGS + - KHR + - KMF + - KPW + - KRW + - KWD + - KYD + - KZT + - LAK + - LBP + - LKR + - LRD + - LSL + - LYD + - MAD + - MDL + - MGA + - MKD + - MMK + - MNT + - MOP + - MRU + - MUR + - MVR + - MWK + - MXN + - MXV + - MYR + - MZN + - NAD + - NGN + - NIO + - NOK + - NPR + - NZD + - OMR + - PAB + - PEN + - PGK + - PHP + - PKR + - PLN + - PYG + - QAR + - RON + - RSD + - RUB + - RWF + - SAR + - SBD + - SCR + - SDG + - SEK + - SGD + - SHP + - SLL + - SOS + - SRD + - SSP + - STN + - SVC + - SYP + - SZL + - THB + - TJS + - TMT + - TND + - TOP + - TRY + - TTD + - TWD + - TZS + - UAH + - UGX + - USD + - USN + - UYI + - UYU + - UYW + - UZS + - VES + - VND + - VUV + - WST + - XAF + - XAG + - XAU + - XBA + - XBB + - XBC + - XBD + - XCD + - XDR + - XOF + - XPD + - XPF + - XPT + - XSU + - XTS + - XUA + - XXX + - YER + - ZAR + - ZMW + - ZWL + BillingCode: + type: string + x-go-custom-tag: gorm:"default:''" + BillPeriod: + type: string + x-go-custom-tag: gorm:"default:monthly" + default: monthly + enum: + - daily + - weekly + - bi-weekly + - monthly + - bi-monthly + - quarterly + - semi-annually + - annually + CancelDate: + type: string + x-go-custom-tag: gorm:"type:date;default:2100-12-31" + format: date + ContractEnd: + type: string + x-go-custom-tag: gorm:"type:date;default:2030-12-31" + format: date + ContractStart: + type: string + x-go-custom-tag: gorm:"type:date;default:2019-01-01" + format: date + Customers: + type: array + x-go-custom-tag: gorm:"-" + items: + $ref: "#/definitions/Customer" + DeletedAt: + type: string + x-go-custom-tag: gorm:"type:timestamptz" + x-nullable: true + format: datetime + EmailBcc: + type: string + x-go-custom-tag: gorm:"default:''" + format: email + EmailCc: + type: string + x-go-custom-tag: gorm:"default:''" + format: email + EmailTo: + type: string + x-go-custom-tag: gorm:"default:''" + format: email + Discount: + type: number + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + format: double + default: 0.0 + InvoiceMode: + type: string + x-go-custom-tag: gorm:"default:email" + default: email + enum: + - email + - post + IsActive: + type: boolean + x-go-custom-tag: gorm:"default:true" + default: true + Language: + type: string + x-go-custom-tag: gorm:"default:DE" + description: ISO-369-1 alpha-2 language codes + default: DE + enum: + - AA + - AB + - AE + - AF + - AK + - AM + - AN + - AR + - AS + - AV + - AY + - AZ + - BA + - BE + - BG + - BH + - BI + - BM + - BN + - BO + - BR + - BS + - CA + - CE + - CH + - CO + - CR + - CS + - CU + - CV + - CY + - DA + - DE + - DV + - DZ + - EE + - EL + - EN + - EO + - ES + - ET + - EU + - FA + - FF + - FI + - FJ + - FO + - FR + - FY + - GA + - GD + - GL + - GN + - GU + - GV + - HA + - HE + - HI + - HO + - HR + - HT + - HU + - HY + - HZ + - IA + - ID + - IE + - IG + - II + - IK + - IO + - IS + - IT + - IU + - JA + - JV + - KA + - KG + - KI + - KJ + - KK + - KL + - KM + - KN + - KO + - KR + - KS + - KU + - KV + - KW + - KY + - LA + - LB + - LG + - LI + - LN + - LO + - LT + - LU + - LV + - MG + - MH + - MI + - MK + - ML + - MN + - MR + - MS + - MT + - MY + - NA + - NB + - ND + - NE + - NG + - NL + - NN + - "NO" + - NR + - NV + - NY + - OC + - OJ + - OM + - OR + - OS + - PA + - PI + - PL + - PS + - PT + - QU + - RM + - RN + - RO + - RU + - RW + - SA + - SC + - SD + - SE + - SG + - SI + - SK + - SL + - SM + - SN + - SO + - SQ + - SR + - SS + - ST + - SU + - SV + - SW + - TA + - TE + - TG + - TH + - TI + - TK + - TL + - TN + - TO + - TR + - TS + - TT + - TW + - TY + - UG + - UK + - UR + - UZ + - VE + - VI + - VO + - WA + - WO + - XH + - YI + - YO + - ZA + - ZH + - ZU + Name: + type: string + ParentResellerId: + type: string + x-go-custom-tag: gorm:"default:''" + PlanId: + type: string + x-go-custom-tag: gorm:"default:'DEFAULT'" + ResellerId: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" diff --git a/services/eventsengine/README.md b/services/eventsengine/README.md new file mode 100644 index 0000000..c915e17 --- /dev/null +++ b/services/eventsengine/README.md @@ -0,0 +1,26 @@ +# EVENTS ENGINE SERVICE + +Cyclops Engine's Events Engine Service implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + diff --git a/services/eventsengine/client/event_engine_management_api_client.go b/services/eventsengine/client/event_engine_management_api_client.go new file mode 100644 index 0000000..69f82b2 --- /dev/null +++ b/services/eventsengine/client/event_engine_management_api_client.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/event_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/usage_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v1.0" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new event engine management API HTTP client. +func New(c Config) *EventEngineManagementAPI { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(EventEngineManagementAPI) + cli.Transport = transport + cli.EventManagement = event_management.New(transport, strfmt.Default, c.AuthInfo) + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + cli.UsageManagement = usage_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// EventEngineManagementAPI is a client for event engine management API +type EventEngineManagementAPI struct { + EventManagement *event_management.Client + StatusManagement *status_management.Client + TriggerManagement *trigger_management.Client + UsageManagement *usage_management.Client + Transport runtime.ClientTransport +} diff --git a/services/eventsengine/client/event_management/add_event_parameters.go b/services/eventsengine/client/event_management/add_event_parameters.go new file mode 100644 index 0000000..8a97c8b --- /dev/null +++ b/services/eventsengine/client/event_management/add_event_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// NewAddEventParams creates a new AddEventParams object +// with the default values initialized. +func NewAddEventParams() *AddEventParams { + var () + return &AddEventParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewAddEventParamsWithTimeout creates a new AddEventParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewAddEventParamsWithTimeout(timeout time.Duration) *AddEventParams { + var () + return &AddEventParams{ + + timeout: timeout, + } +} + +// NewAddEventParamsWithContext creates a new AddEventParams object +// with the default values initialized, and the ability to set a context for a request +func NewAddEventParamsWithContext(ctx context.Context) *AddEventParams { + var () + return &AddEventParams{ + + Context: ctx, + } +} + +// NewAddEventParamsWithHTTPClient creates a new AddEventParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewAddEventParamsWithHTTPClient(client *http.Client) *AddEventParams { + var () + return &AddEventParams{ + HTTPClient: client, + } +} + +/*AddEventParams contains all the parameters to send to the API endpoint +for the add event operation typically these are written to a http.Request +*/ +type AddEventParams struct { + + /*Event + Event to be added to the system + + */ + Event *models.Event + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the add event params +func (o *AddEventParams) WithTimeout(timeout time.Duration) *AddEventParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the add event params +func (o *AddEventParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the add event params +func (o *AddEventParams) WithContext(ctx context.Context) *AddEventParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the add event params +func (o *AddEventParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the add event params +func (o *AddEventParams) WithHTTPClient(client *http.Client) *AddEventParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the add event params +func (o *AddEventParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEvent adds the event to the add event params +func (o *AddEventParams) WithEvent(event *models.Event) *AddEventParams { + o.SetEvent(event) + return o +} + +// SetEvent adds the event to the add event params +func (o *AddEventParams) SetEvent(event *models.Event) { + o.Event = event +} + +// WriteToRequest writes these params to a swagger request +func (o *AddEventParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Event != nil { + if err := r.SetBodyParam(o.Event); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/event_management/add_event_responses.go b/services/eventsengine/client/event_management/add_event_responses.go new file mode 100644 index 0000000..81a23f9 --- /dev/null +++ b/services/eventsengine/client/event_management/add_event_responses.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// AddEventReader is a Reader for the AddEvent structure. +type AddEventReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *AddEventReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewAddEventCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewAddEventBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewAddEventInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewAddEventCreated creates a AddEventCreated with default headers values +func NewAddEventCreated() *AddEventCreated { + return &AddEventCreated{} +} + +/*AddEventCreated handles this case with default header values. + +Item added successfully +*/ +type AddEventCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *AddEventCreated) Error() string { + return fmt.Sprintf("[POST /event][%d] addEventCreated %+v", 201, o.Payload) +} + +func (o *AddEventCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *AddEventCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewAddEventBadRequest creates a AddEventBadRequest with default headers values +func NewAddEventBadRequest() *AddEventBadRequest { + return &AddEventBadRequest{} +} + +/*AddEventBadRequest handles this case with default header values. + +Invalid input, object invalid +*/ +type AddEventBadRequest struct { +} + +func (o *AddEventBadRequest) Error() string { + return fmt.Sprintf("[POST /event][%d] addEventBadRequest ", 400) +} + +func (o *AddEventBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewAddEventInternalServerError creates a AddEventInternalServerError with default headers values +func NewAddEventInternalServerError() *AddEventInternalServerError { + return &AddEventInternalServerError{} +} + +/*AddEventInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type AddEventInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *AddEventInternalServerError) Error() string { + return fmt.Sprintf("[POST /event][%d] addEventInternalServerError %+v", 500, o.Payload) +} + +func (o *AddEventInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *AddEventInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/event_management/event_management_client.go b/services/eventsengine/client/event_management/event_management_client.go new file mode 100644 index 0000000..59400f5 --- /dev/null +++ b/services/eventsengine/client/event_management/event_management_client.go @@ -0,0 +1,150 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the event management client +type API interface { + /* + AddEvent takes into the system the provided event*/ + AddEvent(ctx context.Context, params *AddEventParams) (*AddEventCreated, error) + /* + GetHistory provides the events for the id provided*/ + GetHistory(ctx context.Context, params *GetHistoryParams) (*GetHistoryOK, error) + /* + GetState provides the events for the id provided*/ + GetState(ctx context.Context, params *GetStateParams) (*GetStateOK, error) + /* + ListStates provides the list of states in not terminated state*/ + ListStates(ctx context.Context, params *ListStatesParams) (*ListStatesOK, error) +} + +// New creates a new event management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for event management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +AddEvent takes into the system the provided event +*/ +func (a *Client) AddEvent(ctx context.Context, params *AddEventParams) (*AddEventCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "addEvent", + Method: "POST", + PathPattern: "/event", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &AddEventReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*AddEventCreated), nil + +} + +/* +GetHistory provides the events for the id provided +*/ +func (a *Client) GetHistory(ctx context.Context, params *GetHistoryParams) (*GetHistoryOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getHistory", + Method: "GET", + PathPattern: "/event/history/{account}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetHistoryReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetHistoryOK), nil + +} + +/* +GetState provides the events for the id provided +*/ +func (a *Client) GetState(ctx context.Context, params *GetStateParams) (*GetStateOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getState", + Method: "GET", + PathPattern: "/event/status/{account}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStateReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStateOK), nil + +} + +/* +ListStates provides the list of states in not terminated state +*/ +func (a *Client) ListStates(ctx context.Context, params *ListStatesParams) (*ListStatesOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listStates", + Method: "GET", + PathPattern: "/event/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListStatesReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListStatesOK), nil + +} diff --git a/services/eventsengine/client/event_management/get_history_parameters.go b/services/eventsengine/client/event_management/get_history_parameters.go new file mode 100644 index 0000000..65f7f3d --- /dev/null +++ b/services/eventsengine/client/event_management/get_history_parameters.go @@ -0,0 +1,264 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetHistoryParams creates a new GetHistoryParams object +// with the default values initialized. +func NewGetHistoryParams() *GetHistoryParams { + var () + return &GetHistoryParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetHistoryParamsWithTimeout creates a new GetHistoryParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetHistoryParamsWithTimeout(timeout time.Duration) *GetHistoryParams { + var () + return &GetHistoryParams{ + + timeout: timeout, + } +} + +// NewGetHistoryParamsWithContext creates a new GetHistoryParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetHistoryParamsWithContext(ctx context.Context) *GetHistoryParams { + var () + return &GetHistoryParams{ + + Context: ctx, + } +} + +// NewGetHistoryParamsWithHTTPClient creates a new GetHistoryParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetHistoryParamsWithHTTPClient(client *http.Client) *GetHistoryParams { + var () + return &GetHistoryParams{ + HTTPClient: client, + } +} + +/*GetHistoryParams contains all the parameters to send to the API endpoint +for the get history operation typically these are written to a http.Request +*/ +type GetHistoryParams struct { + + /*Account + Id of the account to be checked + + */ + Account string + /*From + Datetime from which to get the usage report + + */ + From *int64 + /*Region + Resource region to filter the usage + + */ + Region *string + /*Resource + Resource type to filter the usage + + */ + Resource *string + /*To + Datetime until which to get the usage report + + */ + To *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get history params +func (o *GetHistoryParams) WithTimeout(timeout time.Duration) *GetHistoryParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get history params +func (o *GetHistoryParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get history params +func (o *GetHistoryParams) WithContext(ctx context.Context) *GetHistoryParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get history params +func (o *GetHistoryParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get history params +func (o *GetHistoryParams) WithHTTPClient(client *http.Client) *GetHistoryParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get history params +func (o *GetHistoryParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAccount adds the account to the get history params +func (o *GetHistoryParams) WithAccount(account string) *GetHistoryParams { + o.SetAccount(account) + return o +} + +// SetAccount adds the account to the get history params +func (o *GetHistoryParams) SetAccount(account string) { + o.Account = account +} + +// WithFrom adds the from to the get history params +func (o *GetHistoryParams) WithFrom(from *int64) *GetHistoryParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get history params +func (o *GetHistoryParams) SetFrom(from *int64) { + o.From = from +} + +// WithRegion adds the region to the get history params +func (o *GetHistoryParams) WithRegion(region *string) *GetHistoryParams { + o.SetRegion(region) + return o +} + +// SetRegion adds the region to the get history params +func (o *GetHistoryParams) SetRegion(region *string) { + o.Region = region +} + +// WithResource adds the resource to the get history params +func (o *GetHistoryParams) WithResource(resource *string) *GetHistoryParams { + o.SetResource(resource) + return o +} + +// SetResource adds the resource to the get history params +func (o *GetHistoryParams) SetResource(resource *string) { + o.Resource = resource +} + +// WithTo adds the to to the get history params +func (o *GetHistoryParams) WithTo(to *int64) *GetHistoryParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get history params +func (o *GetHistoryParams) SetTo(to *int64) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetHistoryParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param account + if err := r.SetPathParam("account", o.Account); err != nil { + return err + } + + if o.From != nil { + + // query param from + var qrFrom int64 + if o.From != nil { + qrFrom = *o.From + } + qFrom := swag.FormatInt64(qrFrom) + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + if o.Region != nil { + + // query param region + var qrRegion string + if o.Region != nil { + qrRegion = *o.Region + } + qRegion := qrRegion + if qRegion != "" { + if err := r.SetQueryParam("region", qRegion); err != nil { + return err + } + } + + } + + if o.Resource != nil { + + // query param resource + var qrResource string + if o.Resource != nil { + qrResource = *o.Resource + } + qResource := qrResource + if qResource != "" { + if err := r.SetQueryParam("resource", qResource); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo int64 + if o.To != nil { + qrTo = *o.To + } + qTo := swag.FormatInt64(qrTo) + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/event_management/get_history_responses.go b/services/eventsengine/client/event_management/get_history_responses.go new file mode 100644 index 0000000..2f64b1e --- /dev/null +++ b/services/eventsengine/client/event_management/get_history_responses.go @@ -0,0 +1,145 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetHistoryReader is a Reader for the GetHistory structure. +type GetHistoryReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetHistoryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetHistoryOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetHistoryNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetHistoryInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetHistoryOK creates a GetHistoryOK with default headers values +func NewGetHistoryOK() *GetHistoryOK { + return &GetHistoryOK{} +} + +/*GetHistoryOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetHistoryOK struct { + Payload []*models.Event +} + +func (o *GetHistoryOK) Error() string { + return fmt.Sprintf("[GET /event/history/{account}][%d] getHistoryOK %+v", 200, o.Payload) +} + +func (o *GetHistoryOK) GetPayload() []*models.Event { + return o.Payload +} + +func (o *GetHistoryOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetHistoryNotFound creates a GetHistoryNotFound with default headers values +func NewGetHistoryNotFound() *GetHistoryNotFound { + return &GetHistoryNotFound{} +} + +/*GetHistoryNotFound handles this case with default header values. + +Item not found in the system +*/ +type GetHistoryNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetHistoryNotFound) Error() string { + return fmt.Sprintf("[GET /event/history/{account}][%d] getHistoryNotFound %+v", 404, o.Payload) +} + +func (o *GetHistoryNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetHistoryNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetHistoryInternalServerError creates a GetHistoryInternalServerError with default headers values +func NewGetHistoryInternalServerError() *GetHistoryInternalServerError { + return &GetHistoryInternalServerError{} +} + +/*GetHistoryInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetHistoryInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetHistoryInternalServerError) Error() string { + return fmt.Sprintf("[GET /event/history/{account}][%d] getHistoryInternalServerError %+v", 500, o.Payload) +} + +func (o *GetHistoryInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetHistoryInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/event_management/get_state_parameters.go b/services/eventsengine/client/event_management/get_state_parameters.go new file mode 100644 index 0000000..abe506c --- /dev/null +++ b/services/eventsengine/client/event_management/get_state_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStateParams creates a new GetStateParams object +// with the default values initialized. +func NewGetStateParams() *GetStateParams { + var () + return &GetStateParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStateParamsWithTimeout creates a new GetStateParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStateParamsWithTimeout(timeout time.Duration) *GetStateParams { + var () + return &GetStateParams{ + + timeout: timeout, + } +} + +// NewGetStateParamsWithContext creates a new GetStateParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStateParamsWithContext(ctx context.Context) *GetStateParams { + var () + return &GetStateParams{ + + Context: ctx, + } +} + +// NewGetStateParamsWithHTTPClient creates a new GetStateParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStateParamsWithHTTPClient(client *http.Client) *GetStateParams { + var () + return &GetStateParams{ + HTTPClient: client, + } +} + +/*GetStateParams contains all the parameters to send to the API endpoint +for the get state operation typically these are written to a http.Request +*/ +type GetStateParams struct { + + /*Account + Id of the account to be checked + + */ + Account string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get state params +func (o *GetStateParams) WithTimeout(timeout time.Duration) *GetStateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get state params +func (o *GetStateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get state params +func (o *GetStateParams) WithContext(ctx context.Context) *GetStateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get state params +func (o *GetStateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get state params +func (o *GetStateParams) WithHTTPClient(client *http.Client) *GetStateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get state params +func (o *GetStateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAccount adds the account to the get state params +func (o *GetStateParams) WithAccount(account string) *GetStateParams { + o.SetAccount(account) + return o +} + +// SetAccount adds the account to the get state params +func (o *GetStateParams) SetAccount(account string) { + o.Account = account +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param account + if err := r.SetPathParam("account", o.Account); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/event_management/get_state_responses.go b/services/eventsengine/client/event_management/get_state_responses.go new file mode 100644 index 0000000..f5b8362 --- /dev/null +++ b/services/eventsengine/client/event_management/get_state_responses.go @@ -0,0 +1,145 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetStateReader is a Reader for the GetState structure. +type GetStateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStateNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetStateInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStateOK creates a GetStateOK with default headers values +func NewGetStateOK() *GetStateOK { + return &GetStateOK{} +} + +/*GetStateOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetStateOK struct { + Payload []*models.State +} + +func (o *GetStateOK) Error() string { + return fmt.Sprintf("[GET /event/status/{account}][%d] getStateOK %+v", 200, o.Payload) +} + +func (o *GetStateOK) GetPayload() []*models.State { + return o.Payload +} + +func (o *GetStateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStateNotFound creates a GetStateNotFound with default headers values +func NewGetStateNotFound() *GetStateNotFound { + return &GetStateNotFound{} +} + +/*GetStateNotFound handles this case with default header values. + +Item not found in the system +*/ +type GetStateNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStateNotFound) Error() string { + return fmt.Sprintf("[GET /event/status/{account}][%d] getStateNotFound %+v", 404, o.Payload) +} + +func (o *GetStateNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStateNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStateInternalServerError creates a GetStateInternalServerError with default headers values +func NewGetStateInternalServerError() *GetStateInternalServerError { + return &GetStateInternalServerError{} +} + +/*GetStateInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetStateInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetStateInternalServerError) Error() string { + return fmt.Sprintf("[GET /event/status/{account}][%d] getStateInternalServerError %+v", 500, o.Payload) +} + +func (o *GetStateInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStateInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/event_management/list_states_parameters.go b/services/eventsengine/client/event_management/list_states_parameters.go new file mode 100644 index 0000000..1d3fd48 --- /dev/null +++ b/services/eventsengine/client/event_management/list_states_parameters.go @@ -0,0 +1,178 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListStatesParams creates a new ListStatesParams object +// with the default values initialized. +func NewListStatesParams() *ListStatesParams { + var () + return &ListStatesParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListStatesParamsWithTimeout creates a new ListStatesParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListStatesParamsWithTimeout(timeout time.Duration) *ListStatesParams { + var () + return &ListStatesParams{ + + timeout: timeout, + } +} + +// NewListStatesParamsWithContext creates a new ListStatesParams object +// with the default values initialized, and the ability to set a context for a request +func NewListStatesParamsWithContext(ctx context.Context) *ListStatesParams { + var () + return &ListStatesParams{ + + Context: ctx, + } +} + +// NewListStatesParamsWithHTTPClient creates a new ListStatesParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListStatesParamsWithHTTPClient(client *http.Client) *ListStatesParams { + var () + return &ListStatesParams{ + HTTPClient: client, + } +} + +/*ListStatesParams contains all the parameters to send to the API endpoint +for the list states operation typically these are written to a http.Request +*/ +type ListStatesParams struct { + + /*Region + Resource region to filter the usage + + */ + Region *string + /*Resource + Resource type to filter the usage + + */ + Resource *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list states params +func (o *ListStatesParams) WithTimeout(timeout time.Duration) *ListStatesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list states params +func (o *ListStatesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list states params +func (o *ListStatesParams) WithContext(ctx context.Context) *ListStatesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list states params +func (o *ListStatesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list states params +func (o *ListStatesParams) WithHTTPClient(client *http.Client) *ListStatesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list states params +func (o *ListStatesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithRegion adds the region to the list states params +func (o *ListStatesParams) WithRegion(region *string) *ListStatesParams { + o.SetRegion(region) + return o +} + +// SetRegion adds the region to the list states params +func (o *ListStatesParams) SetRegion(region *string) { + o.Region = region +} + +// WithResource adds the resource to the list states params +func (o *ListStatesParams) WithResource(resource *string) *ListStatesParams { + o.SetResource(resource) + return o +} + +// SetResource adds the resource to the list states params +func (o *ListStatesParams) SetResource(resource *string) { + o.Resource = resource +} + +// WriteToRequest writes these params to a swagger request +func (o *ListStatesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Region != nil { + + // query param region + var qrRegion string + if o.Region != nil { + qrRegion = *o.Region + } + qRegion := qrRegion + if qRegion != "" { + if err := r.SetQueryParam("region", qRegion); err != nil { + return err + } + } + + } + + if o.Resource != nil { + + // query param resource + var qrResource string + if o.Resource != nil { + qrResource = *o.Resource + } + qResource := qrResource + if qResource != "" { + if err := r.SetQueryParam("resource", qResource); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/event_management/list_states_responses.go b/services/eventsengine/client/event_management/list_states_responses.go new file mode 100644 index 0000000..6545eb7 --- /dev/null +++ b/services/eventsengine/client/event_management/list_states_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// ListStatesReader is a Reader for the ListStates structure. +type ListStatesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListStatesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListStatesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListStatesInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListStatesOK creates a ListStatesOK with default headers values +func NewListStatesOK() *ListStatesOK { + return &ListStatesOK{} +} + +/*ListStatesOK handles this case with default header values. + +Description of a successfully operation +*/ +type ListStatesOK struct { + Payload []*models.MinimalState +} + +func (o *ListStatesOK) Error() string { + return fmt.Sprintf("[GET /event/status][%d] listStatesOK %+v", 200, o.Payload) +} + +func (o *ListStatesOK) GetPayload() []*models.MinimalState { + return o.Payload +} + +func (o *ListStatesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListStatesInternalServerError creates a ListStatesInternalServerError with default headers values +func NewListStatesInternalServerError() *ListStatesInternalServerError { + return &ListStatesInternalServerError{} +} + +/*ListStatesInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ListStatesInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListStatesInternalServerError) Error() string { + return fmt.Sprintf("[GET /event/status][%d] listStatesInternalServerError %+v", 500, o.Payload) +} + +func (o *ListStatesInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListStatesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/status_management/get_status_parameters.go b/services/eventsengine/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..bc38256 --- /dev/null +++ b/services/eventsengine/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the endpoint to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/status_management/get_status_responses.go b/services/eventsengine/client/status_management/get_status_responses.go new file mode 100644 index 0000000..c9714ca --- /dev/null +++ b/services/eventsengine/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/status_management/show_status_parameters.go b/services/eventsengine/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/services/eventsengine/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/status_management/show_status_responses.go b/services/eventsengine/client/status_management/show_status_responses.go new file mode 100644 index 0000000..4688258 --- /dev/null +++ b/services/eventsengine/client/status_management/show_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewShowStatusInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewShowStatusInternalServerError creates a ShowStatusInternalServerError with default headers values +func NewShowStatusInternalServerError() *ShowStatusInternalServerError { + return &ShowStatusInternalServerError{} +} + +/*ShowStatusInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ShowStatusInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ShowStatusInternalServerError) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusInternalServerError %+v", 500, o.Payload) +} + +func (o *ShowStatusInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ShowStatusInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/status_management/status_management_client.go b/services/eventsengine/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/services/eventsengine/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/services/eventsengine/client/trigger_management/exec_sample_parameters.go b/services/eventsengine/client/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..2e1428d --- /dev/null +++ b/services/eventsengine/client/trigger_management/exec_sample_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// with the default values initialized. +func NewExecSampleParams() *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewExecSampleParamsWithTimeout creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewExecSampleParamsWithTimeout(timeout time.Duration) *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: timeout, + } +} + +// NewExecSampleParamsWithContext creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a context for a request +func NewExecSampleParamsWithContext(ctx context.Context) *ExecSampleParams { + + return &ExecSampleParams{ + + Context: ctx, + } +} + +// NewExecSampleParamsWithHTTPClient creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewExecSampleParamsWithHTTPClient(client *http.Client) *ExecSampleParams { + + return &ExecSampleParams{ + HTTPClient: client, + } +} + +/*ExecSampleParams contains all the parameters to send to the API endpoint +for the exec sample operation typically these are written to a http.Request +*/ +type ExecSampleParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) WithTimeout(timeout time.Duration) *ExecSampleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the exec sample params +func (o *ExecSampleParams) WithContext(ctx context.Context) *ExecSampleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the exec sample params +func (o *ExecSampleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) WithHTTPClient(client *http.Client) *ExecSampleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ExecSampleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/trigger_management/exec_sample_responses.go b/services/eventsengine/client/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..db003a5 --- /dev/null +++ b/services/eventsengine/client/trigger_management/exec_sample_responses.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// ExecSampleReader is a Reader for the ExecSample structure. +type ExecSampleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ExecSampleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewExecSampleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewExecSampleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewExecSampleOK creates a ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + return &ExecSampleOK{} +} + +/*ExecSampleOK handles this case with default header values. + +Sample task executed successfully +*/ +type ExecSampleOK struct { +} + +func (o *ExecSampleOK) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleOK ", 200) +} + +func (o *ExecSampleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewExecSampleInternalServerError creates a ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + return &ExecSampleInternalServerError{} +} + +/*ExecSampleInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ExecSampleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ExecSampleInternalServerError) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleInternalServerError %+v", 500, o.Payload) +} + +func (o *ExecSampleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ExecSampleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/trigger_management/trigger_management_client.go b/services/eventsengine/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..b8010e0 --- /dev/null +++ b/services/eventsengine/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + ExecSample samples task trigger*/ + ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +ExecSample samples task trigger +*/ +func (a *Client) ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "execSample", + Method: "GET", + PathPattern: "/trigger/sample", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ExecSampleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ExecSampleOK), nil + +} diff --git a/services/eventsengine/client/usage_management/get_system_usage_parameters.go b/services/eventsengine/client/usage_management/get_system_usage_parameters.go new file mode 100644 index 0000000..f8ea2b9 --- /dev/null +++ b/services/eventsengine/client/usage_management/get_system_usage_parameters.go @@ -0,0 +1,243 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetSystemUsageParams creates a new GetSystemUsageParams object +// with the default values initialized. +func NewGetSystemUsageParams() *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSystemUsageParamsWithTimeout creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSystemUsageParamsWithTimeout(timeout time.Duration) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + timeout: timeout, + } +} + +// NewGetSystemUsageParamsWithContext creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSystemUsageParamsWithContext(ctx context.Context) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + Context: ctx, + } +} + +// NewGetSystemUsageParamsWithHTTPClient creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSystemUsageParamsWithHTTPClient(client *http.Client) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + HTTPClient: client, + } +} + +/*GetSystemUsageParams contains all the parameters to send to the API endpoint +for the get system usage operation typically these are written to a http.Request +*/ +type GetSystemUsageParams struct { + + /*From + Datetime from which to get the usage report + + */ + From *int64 + /*Region + Resource region to filter the usage + + */ + Region *string + /*Resource + Resource type to filter the usage + + */ + Resource *string + /*To + Datetime until which to get the usage report + + */ + To *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get system usage params +func (o *GetSystemUsageParams) WithTimeout(timeout time.Duration) *GetSystemUsageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get system usage params +func (o *GetSystemUsageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get system usage params +func (o *GetSystemUsageParams) WithContext(ctx context.Context) *GetSystemUsageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get system usage params +func (o *GetSystemUsageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get system usage params +func (o *GetSystemUsageParams) WithHTTPClient(client *http.Client) *GetSystemUsageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get system usage params +func (o *GetSystemUsageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get system usage params +func (o *GetSystemUsageParams) WithFrom(from *int64) *GetSystemUsageParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get system usage params +func (o *GetSystemUsageParams) SetFrom(from *int64) { + o.From = from +} + +// WithRegion adds the region to the get system usage params +func (o *GetSystemUsageParams) WithRegion(region *string) *GetSystemUsageParams { + o.SetRegion(region) + return o +} + +// SetRegion adds the region to the get system usage params +func (o *GetSystemUsageParams) SetRegion(region *string) { + o.Region = region +} + +// WithResource adds the resource to the get system usage params +func (o *GetSystemUsageParams) WithResource(resource *string) *GetSystemUsageParams { + o.SetResource(resource) + return o +} + +// SetResource adds the resource to the get system usage params +func (o *GetSystemUsageParams) SetResource(resource *string) { + o.Resource = resource +} + +// WithTo adds the to to the get system usage params +func (o *GetSystemUsageParams) WithTo(to *int64) *GetSystemUsageParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get system usage params +func (o *GetSystemUsageParams) SetTo(to *int64) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSystemUsageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom int64 + if o.From != nil { + qrFrom = *o.From + } + qFrom := swag.FormatInt64(qrFrom) + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + if o.Region != nil { + + // query param region + var qrRegion string + if o.Region != nil { + qrRegion = *o.Region + } + qRegion := qrRegion + if qRegion != "" { + if err := r.SetQueryParam("region", qRegion); err != nil { + return err + } + } + + } + + if o.Resource != nil { + + // query param resource + var qrResource string + if o.Resource != nil { + qrResource = *o.Resource + } + qResource := qrResource + if qResource != "" { + if err := r.SetQueryParam("resource", qResource); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo int64 + if o.To != nil { + qrTo = *o.To + } + qTo := swag.FormatInt64(qrTo) + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/usage_management/get_system_usage_responses.go b/services/eventsengine/client/usage_management/get_system_usage_responses.go new file mode 100644 index 0000000..b0592d3 --- /dev/null +++ b/services/eventsengine/client/usage_management/get_system_usage_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetSystemUsageReader is a Reader for the GetSystemUsage structure. +type GetSystemUsageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSystemUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSystemUsageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewGetSystemUsageInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetSystemUsageOK creates a GetSystemUsageOK with default headers values +func NewGetSystemUsageOK() *GetSystemUsageOK { + return &GetSystemUsageOK{} +} + +/*GetSystemUsageOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetSystemUsageOK struct { + Payload []*models.Usage +} + +func (o *GetSystemUsageOK) Error() string { + return fmt.Sprintf("[GET /usage][%d] getSystemUsageOK %+v", 200, o.Payload) +} + +func (o *GetSystemUsageOK) GetPayload() []*models.Usage { + return o.Payload +} + +func (o *GetSystemUsageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSystemUsageInternalServerError creates a GetSystemUsageInternalServerError with default headers values +func NewGetSystemUsageInternalServerError() *GetSystemUsageInternalServerError { + return &GetSystemUsageInternalServerError{} +} + +/*GetSystemUsageInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetSystemUsageInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetSystemUsageInternalServerError) Error() string { + return fmt.Sprintf("[GET /usage][%d] getSystemUsageInternalServerError %+v", 500, o.Payload) +} + +func (o *GetSystemUsageInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSystemUsageInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/usage_management/get_usage_parameters.go b/services/eventsengine/client/usage_management/get_usage_parameters.go new file mode 100644 index 0000000..a9ccbdc --- /dev/null +++ b/services/eventsengine/client/usage_management/get_usage_parameters.go @@ -0,0 +1,264 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetUsageParams creates a new GetUsageParams object +// with the default values initialized. +func NewGetUsageParams() *GetUsageParams { + var () + return &GetUsageParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetUsageParamsWithTimeout creates a new GetUsageParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetUsageParamsWithTimeout(timeout time.Duration) *GetUsageParams { + var () + return &GetUsageParams{ + + timeout: timeout, + } +} + +// NewGetUsageParamsWithContext creates a new GetUsageParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetUsageParamsWithContext(ctx context.Context) *GetUsageParams { + var () + return &GetUsageParams{ + + Context: ctx, + } +} + +// NewGetUsageParamsWithHTTPClient creates a new GetUsageParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetUsageParamsWithHTTPClient(client *http.Client) *GetUsageParams { + var () + return &GetUsageParams{ + HTTPClient: client, + } +} + +/*GetUsageParams contains all the parameters to send to the API endpoint +for the get usage operation typically these are written to a http.Request +*/ +type GetUsageParams struct { + + /*From + Datetime from which to get the usage report + + */ + From *int64 + /*ID + Id of the account to be checked + + */ + ID string + /*Region + Resource region to filter the usage + + */ + Region *string + /*Resource + Resource type to filter the usage + + */ + Resource *string + /*To + Datetime until which to get the usage report + + */ + To *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get usage params +func (o *GetUsageParams) WithTimeout(timeout time.Duration) *GetUsageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get usage params +func (o *GetUsageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get usage params +func (o *GetUsageParams) WithContext(ctx context.Context) *GetUsageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get usage params +func (o *GetUsageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get usage params +func (o *GetUsageParams) WithHTTPClient(client *http.Client) *GetUsageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get usage params +func (o *GetUsageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get usage params +func (o *GetUsageParams) WithFrom(from *int64) *GetUsageParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get usage params +func (o *GetUsageParams) SetFrom(from *int64) { + o.From = from +} + +// WithID adds the id to the get usage params +func (o *GetUsageParams) WithID(id string) *GetUsageParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get usage params +func (o *GetUsageParams) SetID(id string) { + o.ID = id +} + +// WithRegion adds the region to the get usage params +func (o *GetUsageParams) WithRegion(region *string) *GetUsageParams { + o.SetRegion(region) + return o +} + +// SetRegion adds the region to the get usage params +func (o *GetUsageParams) SetRegion(region *string) { + o.Region = region +} + +// WithResource adds the resource to the get usage params +func (o *GetUsageParams) WithResource(resource *string) *GetUsageParams { + o.SetResource(resource) + return o +} + +// SetResource adds the resource to the get usage params +func (o *GetUsageParams) SetResource(resource *string) { + o.Resource = resource +} + +// WithTo adds the to to the get usage params +func (o *GetUsageParams) WithTo(to *int64) *GetUsageParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get usage params +func (o *GetUsageParams) SetTo(to *int64) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetUsageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom int64 + if o.From != nil { + qrFrom = *o.From + } + qFrom := swag.FormatInt64(qrFrom) + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Region != nil { + + // query param region + var qrRegion string + if o.Region != nil { + qrRegion = *o.Region + } + qRegion := qrRegion + if qRegion != "" { + if err := r.SetQueryParam("region", qRegion); err != nil { + return err + } + } + + } + + if o.Resource != nil { + + // query param resource + var qrResource string + if o.Resource != nil { + qrResource = *o.Resource + } + qResource := qrResource + if qResource != "" { + if err := r.SetQueryParam("resource", qResource); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo int64 + if o.To != nil { + qrTo = *o.To + } + qTo := swag.FormatInt64(qrTo) + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/client/usage_management/get_usage_responses.go b/services/eventsengine/client/usage_management/get_usage_responses.go new file mode 100644 index 0000000..eb86551 --- /dev/null +++ b/services/eventsengine/client/usage_management/get_usage_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetUsageReader is a Reader for the GetUsage structure. +type GetUsageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetUsageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetUsageNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetUsageInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetUsageOK creates a GetUsageOK with default headers values +func NewGetUsageOK() *GetUsageOK { + return &GetUsageOK{} +} + +/*GetUsageOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetUsageOK struct { + Payload *models.Usage +} + +func (o *GetUsageOK) Error() string { + return fmt.Sprintf("[GET /usage/{id}][%d] getUsageOK %+v", 200, o.Payload) +} + +func (o *GetUsageOK) GetPayload() *models.Usage { + return o.Payload +} + +func (o *GetUsageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Usage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetUsageNotFound creates a GetUsageNotFound with default headers values +func NewGetUsageNotFound() *GetUsageNotFound { + return &GetUsageNotFound{} +} + +/*GetUsageNotFound handles this case with default header values. + +Item not found in the system +*/ +type GetUsageNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetUsageNotFound) Error() string { + return fmt.Sprintf("[GET /usage/{id}][%d] getUsageNotFound %+v", 404, o.Payload) +} + +func (o *GetUsageNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetUsageNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetUsageInternalServerError creates a GetUsageInternalServerError with default headers values +func NewGetUsageInternalServerError() *GetUsageInternalServerError { + return &GetUsageInternalServerError{} +} + +/*GetUsageInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetUsageInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetUsageInternalServerError) Error() string { + return fmt.Sprintf("[GET /usage/{id}][%d] getUsageInternalServerError %+v", 500, o.Payload) +} + +func (o *GetUsageInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetUsageInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/eventsengine/client/usage_management/usage_management_client.go b/services/eventsengine/client/usage_management/usage_management_client.go new file mode 100644 index 0000000..59c045b --- /dev/null +++ b/services/eventsengine/client/usage_management/usage_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the usage management client +type API interface { + /* + GetSystemUsage generates an aggregated response by account of the usage recorded in the system during the time window specified*/ + GetSystemUsage(ctx context.Context, params *GetSystemUsageParams) (*GetSystemUsageOK, error) + /* + GetUsage generates an aggregated response of the usage recorded in the system during the time window specified for the selected account*/ + GetUsage(ctx context.Context, params *GetUsageParams) (*GetUsageOK, error) +} + +// New creates a new usage management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for usage management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetSystemUsage generates an aggregated response by account of the usage recorded in the system during the time window specified +*/ +func (a *Client) GetSystemUsage(ctx context.Context, params *GetSystemUsageParams) (*GetSystemUsageOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSystemUsage", + Method: "GET", + PathPattern: "/usage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSystemUsageReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSystemUsageOK), nil + +} + +/* +GetUsage generates an aggregated response of the usage recorded in the system during the time window specified for the selected account +*/ +func (a *Client) GetUsage(ctx context.Context, params *GetUsageParams) (*GetUsageOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getUsage", + Method: "GET", + PathPattern: "/usage/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetUsageReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetUsageOK), nil + +} diff --git a/services/eventsengine/go.mod b/services/eventsengine/go.mod new file mode 100644 index 0000000..738905c --- /dev/null +++ b/services/eventsengine/go.mod @@ -0,0 +1,41 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine + +go 1.15 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/go-openapi/analysis v0.21.1 // indirect + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/go-resty/resty/v2 v2.7.0 // indirect + github.com/go-stack/stack v1.8.1 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/jackc/pgx/v4 v4.14.1 // indirect + github.com/jinzhu/now v1.1.4 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/pierrec/lz4 v2.6.1+incompatible // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/remeh/sizedwaitgroup v1.0.0 + github.com/rs/cors v1.8.2 + github.com/segmentio/asm v1.1.3 // indirect + github.com/segmentio/encoding v0.3.2 + github.com/segmentio/kafka-go v0.4.25 + github.com/segmentio/ksuid v1.0.4 // indirect + github.com/spf13/viper v1.10.1 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + go.mongodb.org/mongo-driver v1.8.1 // indirect + golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect + golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect + golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/services/eventsengine/models/error_response.go b/services/eventsengine/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/services/eventsengine/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/models/event.go b/services/eventsengine/models/event.go new file mode 100644 index 0000000..dc5d83b --- /dev/null +++ b/services/eventsengine/models/event.go @@ -0,0 +1,155 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// Event event +// +// swagger:model Event +type Event struct { + + // account + Account string `json:"Account,omitempty" gorm:"index"` + + // event time + // Required: true + EventTime *int64 `json:"EventTime"` + + // ID + ID int64 `json:"ID,omitempty" gorm:"primary_key;auto_increment"` + + // last event + // Required: true + // Enum: [active error inactive terminated suspended] + LastEvent *string `json:"LastEvent"` + + // meta data + MetaData datamodels.JSONdb `json:"MetaData,omitempty" gorm:"type:jsonb"` + + // region + Region string `json:"Region,omitempty"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // time from + TimeFrom int64 `json:"TimeFrom,omitempty" gorm:"index"` + + // time to + TimeTo int64 `json:"TimeTo,omitempty" gorm:"index"` +} + +// Validate validates this event +func (m *Event) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventTime(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLastEvent(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Event) validateEventTime(formats strfmt.Registry) error { + + if err := validate.Required("EventTime", "body", m.EventTime); err != nil { + return err + } + + return nil +} + +var eventTypeLastEventPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["active","error","inactive","terminated","suspended"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + eventTypeLastEventPropEnum = append(eventTypeLastEventPropEnum, v) + } +} + +const ( + + // EventLastEventActive captures enum value "active" + EventLastEventActive string = "active" + + // EventLastEventError captures enum value "error" + EventLastEventError string = "error" + + // EventLastEventInactive captures enum value "inactive" + EventLastEventInactive string = "inactive" + + // EventLastEventTerminated captures enum value "terminated" + EventLastEventTerminated string = "terminated" + + // EventLastEventSuspended captures enum value "suspended" + EventLastEventSuspended string = "suspended" +) + +// prop value enum +func (m *Event) validateLastEventEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, eventTypeLastEventPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *Event) validateLastEvent(formats strfmt.Registry) error { + + if err := validate.Required("LastEvent", "body", m.LastEvent); err != nil { + return err + } + + // value enum + if err := m.validateLastEventEnum("LastEvent", "body", *m.LastEvent); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Event) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Event) UnmarshalBinary(b []byte) error { + var res Event + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/models/item_created_response.go b/services/eventsengine/models/item_created_response.go new file mode 100644 index 0000000..ea34934 --- /dev/null +++ b/services/eventsengine/models/item_created_response.go @@ -0,0 +1,46 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ItemCreatedResponse item created response +// +// swagger:model ItemCreatedResponse +type ItemCreatedResponse struct { + + // Api link + APILink string `json:"ApiLink,omitempty"` + + // message + Message string `json:"Message,omitempty"` +} + +// Validate validates this item created response +func (m *ItemCreatedResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ItemCreatedResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ItemCreatedResponse) UnmarshalBinary(b []byte) error { + var res ItemCreatedResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/models/minimal_state.go b/services/eventsengine/models/minimal_state.go new file mode 100644 index 0000000..dd6c05f --- /dev/null +++ b/services/eventsengine/models/minimal_state.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "gitlab.com/cyclops-utilities/datamodels" +) + +// MinimalState minimal state +// +// swagger:model MinimalState +type MinimalState struct { + + // account + Account string `json:"Account,omitempty"` + + // meta data + MetaData datamodels.JSONdb `json:"MetaData,omitempty" gorm:"type:jsonb"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` +} + +// Validate validates this minimal state +func (m *MinimalState) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *MinimalState) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MinimalState) UnmarshalBinary(b []byte) error { + var res MinimalState + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/models/state.go b/services/eventsengine/models/state.go new file mode 100644 index 0000000..579b61a --- /dev/null +++ b/services/eventsengine/models/state.go @@ -0,0 +1,155 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// State state +// +// swagger:model State +type State struct { + + // account + Account string `json:"Account,omitempty" gorm:"index"` + + // event time + // Required: true + EventTime *int64 `json:"EventTime"` + + // ID + ID int64 `json:"ID,omitempty" gorm:"primary_key;auto_increment"` + + // last event + // Required: true + // Enum: [active error inactive terminated suspended] + LastEvent *string `json:"LastEvent"` + + // meta data + MetaData datamodels.JSONdb `json:"MetaData,omitempty" gorm:"type:jsonb"` + + // region + Region string `json:"Region,omitempty"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // time from + TimeFrom int64 `json:"TimeFrom,omitempty" gorm:"index"` + + // time to + TimeTo int64 `json:"TimeTo,omitempty" gorm:"index"` +} + +// Validate validates this state +func (m *State) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEventTime(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLastEvent(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *State) validateEventTime(formats strfmt.Registry) error { + + if err := validate.Required("EventTime", "body", m.EventTime); err != nil { + return err + } + + return nil +} + +var stateTypeLastEventPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["active","error","inactive","terminated","suspended"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + stateTypeLastEventPropEnum = append(stateTypeLastEventPropEnum, v) + } +} + +const ( + + // StateLastEventActive captures enum value "active" + StateLastEventActive string = "active" + + // StateLastEventError captures enum value "error" + StateLastEventError string = "error" + + // StateLastEventInactive captures enum value "inactive" + StateLastEventInactive string = "inactive" + + // StateLastEventTerminated captures enum value "terminated" + StateLastEventTerminated string = "terminated" + + // StateLastEventSuspended captures enum value "suspended" + StateLastEventSuspended string = "suspended" +) + +// prop value enum +func (m *State) validateLastEventEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, stateTypeLastEventPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *State) validateLastEvent(formats strfmt.Registry) error { + + if err := validate.Required("LastEvent", "body", m.LastEvent); err != nil { + return err + } + + // value enum + if err := m.validateLastEventEnum("LastEvent", "body", *m.LastEvent); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *State) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *State) UnmarshalBinary(b []byte) error { + var res State + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/models/status.go b/services/eventsengine/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/services/eventsengine/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/models/usage.go b/services/eventsengine/models/usage.go new file mode 100644 index 0000000..f9982a0 --- /dev/null +++ b/services/eventsengine/models/usage.go @@ -0,0 +1,89 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Usage usage +// +// swagger:model Usage +type Usage struct { + + // account Id + AccountID string `json:"AccountId,omitempty"` + + // time from + TimeFrom int64 `json:"TimeFrom,omitempty"` + + // time to + TimeTo int64 `json:"TimeTo,omitempty"` + + // usage + Usage []*Use `json:"Usage"` +} + +// Validate validates this usage +func (m *Usage) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateUsage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Usage) validateUsage(formats strfmt.Registry) error { + + if swag.IsZero(m.Usage) { // not required + return nil + } + + for i := 0; i < len(m.Usage); i++ { + if swag.IsZero(m.Usage[i]) { // not required + continue + } + + if m.Usage[i] != nil { + if err := m.Usage[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("Usage" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Usage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Usage) UnmarshalBinary(b []byte) error { + var res Usage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/models/use.go b/services/eventsengine/models/use.go new file mode 100644 index 0000000..20f83d2 --- /dev/null +++ b/services/eventsengine/models/use.go @@ -0,0 +1,62 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "gitlab.com/cyclops-utilities/datamodels" +) + +// Use use +// +// swagger:model Use +type Use struct { + + // meta data + MetaData datamodels.JSONdb `json:"MetaData,omitempty"` + + // region + Region string `json:"Region,omitempty"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // unit + Unit string `json:"Unit,omitempty"` + + // usage breakup + UsageBreakup datamodels.JSONdb `json:"UsageBreakup,omitempty"` +} + +// Validate validates this use +func (m *Use) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Use) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Use) UnmarshalBinary(b []byte) error { + var res Use + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/eventsengine/restapi/configure_event_engine_management_api.go b/services/eventsengine/restapi/configure_event_engine_management_api.go new file mode 100644 index 0000000..e815c14 --- /dev/null +++ b/services/eventsengine/restapi/configure_event_engine_management_api.go @@ -0,0 +1,227 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/event_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/usage_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name EventManagementAPI -inpkg + +/* EventManagementAPI */ +type EventManagementAPI interface { + /* AddEvent Takes into the system the provided event */ + AddEvent(ctx context.Context, params event_management.AddEventParams) middleware.Responder + + /* GetHistory Provides the events for the id provided */ + GetHistory(ctx context.Context, params event_management.GetHistoryParams) middleware.Responder + + /* GetState Provides the events for the id provided */ + GetState(ctx context.Context, params event_management.GetStateParams) middleware.Responder + + /* ListStates Provides the list of states in not terminated state */ + ListStates(ctx context.Context, params event_management.ListStatesParams) middleware.Responder +} + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* ExecSample Sample task trigger */ + ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder +} + +//go:generate mockery -name UsageManagementAPI -inpkg + +/* UsageManagementAPI */ +type UsageManagementAPI interface { + /* GetSystemUsage Generates an aggregated response by account of the usage recorded in the system during the time-window specified */ + GetSystemUsage(ctx context.Context, params usage_management.GetSystemUsageParams) middleware.Responder + + /* GetUsage Generates an aggregated response of the usage recorded in the system during the time-window specified for the selected account */ + GetUsage(ctx context.Context, params usage_management.GetUsageParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + EventManagementAPI + StatusManagementAPI + TriggerManagementAPI + UsageManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) + // Authenticator to use for all APIKey authentication + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // Authenticator to use for all Bearer authentication + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // Authenticator to use for all Basic authentication + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *EventEngineManagementAPI instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.EventEngineManagementAPIAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewEventEngineManagementAPIAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + if c.APIKeyAuthenticator != nil { + api.APIKeyAuthenticator = c.APIKeyAuthenticator + } + if c.BasicAuthenticator != nil { + api.BasicAuthenticator = c.BasicAuthenticator + } + if c.BearerAuthenticator != nil { + api.BearerAuthenticator = c.BearerAuthenticator + } + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.EventManagementAddEventHandler = event_management.AddEventHandlerFunc(func(params event_management.AddEventParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.EventManagementAPI.AddEvent(ctx, params) + }) + api.TriggerManagementExecSampleHandler = trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.ExecSample(ctx, params) + }) + api.EventManagementGetHistoryHandler = event_management.GetHistoryHandlerFunc(func(params event_management.GetHistoryParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.EventManagementAPI.GetHistory(ctx, params) + }) + api.EventManagementGetStateHandler = event_management.GetStateHandlerFunc(func(params event_management.GetStateParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.EventManagementAPI.GetState(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.UsageManagementGetSystemUsageHandler = usage_management.GetSystemUsageHandlerFunc(func(params usage_management.GetSystemUsageParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.UsageManagementAPI.GetSystemUsage(ctx, params) + }) + api.UsageManagementGetUsageHandler = usage_management.GetUsageHandlerFunc(func(params usage_management.GetUsageParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.UsageManagementAPI.GetUsage(ctx, params) + }) + api.EventManagementListStatesHandler = event_management.ListStatesHandlerFunc(func(params event_management.ListStatesParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.EventManagementAPI.ListStates(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/services/eventsengine/restapi/doc.go b/services/eventsengine/restapi/doc.go new file mode 100644 index 0000000..9eca661 --- /dev/null +++ b/services/eventsengine/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi Event Engine Management API +// +// An API which supports creation, deletion, listing etc of Event Engine +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v1.0 +// Version: 1.0.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/services/eventsengine/restapi/embedded_spec.go b/services/eventsengine/restapi/embedded_spec.go new file mode 100644 index 0000000..ec81db5 --- /dev/null +++ b/services/eventsengine/restapi/embedded_spec.go @@ -0,0 +1,1696 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Event Engine", + "title": "Event Engine Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/event": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Takes into the system the provided event", + "operationId": "addEvent", + "parameters": [ + { + "description": "Event to be added to the system", + "name": "event", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Event" + } + } + ], + "responses": { + "201": { + "description": "Item added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/event/history/{account}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Provides the events for the id provided", + "operationId": "getHistory", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "account", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "integer", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Event" + } + } + }, + "404": { + "description": "Item not found in the system", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/event/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Provides the list of states in not terminated state", + "operationId": "listStates", + "parameters": [ + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/MinimalState" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/event/status/{account}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Provides the events for the id provided", + "operationId": "getState", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "account", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/State" + } + } + }, + "404": { + "description": "Item not found in the system", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "status", + "kafka-receiver", + "kafka-sender", + "trigger", + "usage", + "event" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Generates an aggregated response by account of the usage recorded in the system during the time-window specified", + "operationId": "getSystemUsage", + "parameters": [ + { + "type": "integer", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "integer", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Usage" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Generates an aggregated response of the usage recorded in the system during the time-window specified for the selected account", + "operationId": "getUsage", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "integer", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/Usage" + } + }, + "404": { + "description": "Item not found in the system", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Event": { + "type": "object", + "required": [ + "EventTime", + "LastEvent" + ], + "properties": { + "Account": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "EventTime": { + "type": "integer" + }, + "ID": { + "type": "integer", + "x-go-custom-tag": "gorm:\"primary_key;auto_increment\"" + }, + "LastEvent": { + "type": "string", + "enum": [ + "active", + "error", + "inactive", + "terminated", + "suspended" + ] + }, + "MetaData": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Region": { + "type": "string" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeTo": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "MinimalState": { + "type": "object", + "properties": { + "Account": { + "type": "string" + }, + "MetaData": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + } + } + }, + "State": { + "type": "object", + "required": [ + "EventTime", + "LastEvent" + ], + "properties": { + "Account": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "EventTime": { + "type": "integer" + }, + "ID": { + "type": "integer", + "x-go-custom-tag": "gorm:\"primary_key;auto_increment\"" + }, + "LastEvent": { + "type": "string", + "enum": [ + "active", + "error", + "inactive", + "terminated", + "suspended" + ] + }, + "MetaData": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Region": { + "type": "string" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeTo": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "Usage": { + "type": "object", + "properties": { + "AccountId": { + "type": "string" + }, + "TimeFrom": { + "type": "integer" + }, + "TimeTo": { + "type": "integer" + }, + "Usage": { + "type": "array", + "items": { + "$ref": "#/definitions/Use" + } + } + } + }, + "Use": { + "type": "object", + "properties": { + "MetaData": { + "$ref": "#/definitions/Metadata" + }, + "Region": { + "type": "string" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "$ref": "#/definitions/Metadata" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the adquisition of events in the system", + "name": "eventManagement" + }, + { + "description": "Actions relating to the reporting of the usages in the system", + "name": "usageManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Event Engine", + "title": "Event Engine Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/event": { + "post": { + "security": [ + { + "Keycloak": [ + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Takes into the system the provided event", + "operationId": "addEvent", + "parameters": [ + { + "description": "Event to be added to the system", + "name": "event", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Event" + } + } + ], + "responses": { + "201": { + "description": "Item added successfully", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "Invalid input, object invalid" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/event/history/{account}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Provides the events for the id provided", + "operationId": "getHistory", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "account", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "integer", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Event" + } + } + }, + "404": { + "description": "Item not found in the system", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/event/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Provides the list of states in not terminated state", + "operationId": "listStates", + "parameters": [ + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/MinimalState" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/event/status/{account}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "eventManagement" + ], + "summary": "Provides the events for the id provided", + "operationId": "getState", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "account", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/State" + } + } + }, + "404": { + "description": "Item not found in the system", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "status", + "kafka-receiver", + "kafka-sender", + "trigger", + "usage", + "event" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Generates an aggregated response by account of the usage recorded in the system during the time-window specified", + "operationId": "getSystemUsage", + "parameters": [ + { + "type": "integer", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "integer", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Usage" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Generates an aggregated response of the usage recorded in the system during the time-window specified for the selected account", + "operationId": "getUsage", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "integer", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "integer", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Resource type to filter the usage", + "name": "resource", + "in": "query" + }, + { + "type": "string", + "description": "Resource region to filter the usage", + "name": "region", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "$ref": "#/definitions/Usage" + } + }, + "404": { + "description": "Item not found in the system", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Event": { + "type": "object", + "required": [ + "EventTime", + "LastEvent" + ], + "properties": { + "Account": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "EventTime": { + "type": "integer" + }, + "ID": { + "type": "integer", + "x-go-custom-tag": "gorm:\"primary_key;auto_increment\"" + }, + "LastEvent": { + "type": "string", + "enum": [ + "active", + "error", + "inactive", + "terminated", + "suspended" + ] + }, + "MetaData": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Region": { + "type": "string" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeTo": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ApiLink": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "MinimalState": { + "type": "object", + "properties": { + "Account": { + "type": "string" + }, + "MetaData": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + } + } + }, + "State": { + "type": "object", + "required": [ + "EventTime", + "LastEvent" + ], + "properties": { + "Account": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "EventTime": { + "type": "integer" + }, + "ID": { + "type": "integer", + "x-go-custom-tag": "gorm:\"primary_key;auto_increment\"" + }, + "LastEvent": { + "type": "string", + "enum": [ + "active", + "error", + "inactive", + "terminated", + "suspended" + ] + }, + "MetaData": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "Region": { + "type": "string" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeTo": { + "type": "integer", + "x-go-custom-tag": "gorm:\"index\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "Usage": { + "type": "object", + "properties": { + "AccountId": { + "type": "string" + }, + "TimeFrom": { + "type": "integer" + }, + "TimeTo": { + "type": "integer" + }, + "Usage": { + "type": "array", + "items": { + "$ref": "#/definitions/Use" + } + } + } + }, + "Use": { + "type": "object", + "properties": { + "MetaData": { + "$ref": "#/definitions/Metadata" + }, + "Region": { + "type": "string" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "$ref": "#/definitions/Metadata" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the adquisition of events in the system", + "name": "eventManagement" + }, + { + "description": "Actions relating to the reporting of the usages in the system", + "name": "usageManagement" + } + ] +}`)) +} diff --git a/services/eventsengine/restapi/operations/event_engine_management_api_api.go b/services/eventsengine/restapi/operations/event_engine_management_api_api.go new file mode 100644 index 0000000..31aa30d --- /dev/null +++ b/services/eventsengine/restapi/operations/event_engine_management_api_api.go @@ -0,0 +1,454 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/event_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/usage_management" +) + +// NewEventEngineManagementAPIAPI creates a new EventEngineManagementAPI instance +func NewEventEngineManagementAPIAPI(spec *loads.Document) *EventEngineManagementAPIAPI { + return &EventEngineManagementAPIAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + useSwaggerUI: false, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + EventManagementAddEventHandler: event_management.AddEventHandlerFunc(func(params event_management.AddEventParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation event_management.AddEvent has not yet been implemented") + }), + TriggerManagementExecSampleHandler: trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.ExecSample has not yet been implemented") + }), + EventManagementGetHistoryHandler: event_management.GetHistoryHandlerFunc(func(params event_management.GetHistoryParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation event_management.GetHistory has not yet been implemented") + }), + EventManagementGetStateHandler: event_management.GetStateHandlerFunc(func(params event_management.GetStateParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation event_management.GetState has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + UsageManagementGetSystemUsageHandler: usage_management.GetSystemUsageHandlerFunc(func(params usage_management.GetSystemUsageParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation usage_management.GetSystemUsage has not yet been implemented") + }), + UsageManagementGetUsageHandler: usage_management.GetUsageHandlerFunc(func(params usage_management.GetUsageParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation usage_management.GetUsage has not yet been implemented") + }), + EventManagementListStatesHandler: event_management.ListStatesHandlerFunc(func(params event_management.ListStatesParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation event_management.ListStates has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*EventEngineManagementAPIAPI An API which supports creation, deletion, listing etc of Event Engine */ +type EventEngineManagementAPIAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + useSwaggerUI bool + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // EventManagementAddEventHandler sets the operation handler for the add event operation + EventManagementAddEventHandler event_management.AddEventHandler + // TriggerManagementExecSampleHandler sets the operation handler for the exec sample operation + TriggerManagementExecSampleHandler trigger_management.ExecSampleHandler + // EventManagementGetHistoryHandler sets the operation handler for the get history operation + EventManagementGetHistoryHandler event_management.GetHistoryHandler + // EventManagementGetStateHandler sets the operation handler for the get state operation + EventManagementGetStateHandler event_management.GetStateHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // UsageManagementGetSystemUsageHandler sets the operation handler for the get system usage operation + UsageManagementGetSystemUsageHandler usage_management.GetSystemUsageHandler + // UsageManagementGetUsageHandler sets the operation handler for the get usage operation + UsageManagementGetUsageHandler usage_management.GetUsageHandler + // EventManagementListStatesHandler sets the operation handler for the list states operation + EventManagementListStatesHandler event_management.ListStatesHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// UseRedoc for documentation at /docs +func (o *EventEngineManagementAPIAPI) UseRedoc() { + o.useSwaggerUI = false +} + +// UseSwaggerUI for documentation at /docs +func (o *EventEngineManagementAPIAPI) UseSwaggerUI() { + o.useSwaggerUI = true +} + +// SetDefaultProduces sets the default produces media type +func (o *EventEngineManagementAPIAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *EventEngineManagementAPIAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *EventEngineManagementAPIAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *EventEngineManagementAPIAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *EventEngineManagementAPIAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *EventEngineManagementAPIAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *EventEngineManagementAPIAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the EventEngineManagementAPIAPI +func (o *EventEngineManagementAPIAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.EventManagementAddEventHandler == nil { + unregistered = append(unregistered, "event_management.AddEventHandler") + } + if o.TriggerManagementExecSampleHandler == nil { + unregistered = append(unregistered, "trigger_management.ExecSampleHandler") + } + if o.EventManagementGetHistoryHandler == nil { + unregistered = append(unregistered, "event_management.GetHistoryHandler") + } + if o.EventManagementGetStateHandler == nil { + unregistered = append(unregistered, "event_management.GetStateHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.UsageManagementGetSystemUsageHandler == nil { + unregistered = append(unregistered, "usage_management.GetSystemUsageHandler") + } + if o.UsageManagementGetUsageHandler == nil { + unregistered = append(unregistered, "usage_management.GetUsageHandler") + } + if o.EventManagementListStatesHandler == nil { + unregistered = append(unregistered, "event_management.ListStatesHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *EventEngineManagementAPIAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *EventEngineManagementAPIAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *EventEngineManagementAPIAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *EventEngineManagementAPIAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *EventEngineManagementAPIAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *EventEngineManagementAPIAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the event engine management API API +func (o *EventEngineManagementAPIAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *EventEngineManagementAPIAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/event"] = event_management.NewAddEvent(o.context, o.EventManagementAddEventHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/sample"] = trigger_management.NewExecSample(o.context, o.TriggerManagementExecSampleHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/event/history/{account}"] = event_management.NewGetHistory(o.context, o.EventManagementGetHistoryHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/event/status/{account}"] = event_management.NewGetState(o.context, o.EventManagementGetStateHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/usage"] = usage_management.NewGetSystemUsage(o.context, o.UsageManagementGetSystemUsageHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/usage/{id}"] = usage_management.NewGetUsage(o.context, o.UsageManagementGetUsageHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/event/status"] = event_management.NewListStates(o.context, o.EventManagementListStatesHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *EventEngineManagementAPIAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + if o.useSwaggerUI { + return o.context.APIHandlerSwaggerUI(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *EventEngineManagementAPIAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *EventEngineManagementAPIAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *EventEngineManagementAPIAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *EventEngineManagementAPIAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/services/eventsengine/restapi/operations/event_management/add_event.go b/services/eventsengine/restapi/operations/event_management/add_event.go new file mode 100644 index 0000000..92a08ea --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/add_event.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// AddEventHandlerFunc turns a function with the right signature into a add event handler +type AddEventHandlerFunc func(AddEventParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn AddEventHandlerFunc) Handle(params AddEventParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// AddEventHandler interface for that can handle valid add event params +type AddEventHandler interface { + Handle(AddEventParams, interface{}) middleware.Responder +} + +// NewAddEvent creates a new http.Handler for the add event operation +func NewAddEvent(ctx *middleware.Context, handler AddEventHandler) *AddEvent { + return &AddEvent{Context: ctx, Handler: handler} +} + +/*AddEvent swagger:route POST /event eventManagement addEvent + +Takes into the system the provided event + +*/ +type AddEvent struct { + Context *middleware.Context + Handler AddEventHandler +} + +func (o *AddEvent) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewAddEventParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/event_management/add_event_parameters.go b/services/eventsengine/restapi/operations/event_management/add_event_parameters.go new file mode 100644 index 0000000..511a32f --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/add_event_parameters.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// NewAddEventParams creates a new AddEventParams object +// no default values defined in spec. +func NewAddEventParams() AddEventParams { + + return AddEventParams{} +} + +// AddEventParams contains all the bound params for the add event operation +// typically these are obtained from a http.Request +// +// swagger:parameters addEvent +type AddEventParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Event to be added to the system + Required: true + In: body + */ + Event *models.Event +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewAddEventParams() beforehand. +func (o *AddEventParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Event + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("event", "body", "")) + } else { + res = append(res, errors.NewParseError("event", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Event = &body + } + } + } else { + res = append(res, errors.Required("event", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/restapi/operations/event_management/add_event_responses.go b/services/eventsengine/restapi/operations/event_management/add_event_responses.go new file mode 100644 index 0000000..c555fad --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/add_event_responses.go @@ -0,0 +1,126 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// AddEventCreatedCode is the HTTP code returned for type AddEventCreated +const AddEventCreatedCode int = 201 + +/*AddEventCreated Item added successfully + +swagger:response addEventCreated +*/ +type AddEventCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewAddEventCreated creates AddEventCreated with default headers values +func NewAddEventCreated() *AddEventCreated { + + return &AddEventCreated{} +} + +// WithPayload adds the payload to the add event created response +func (o *AddEventCreated) WithPayload(payload *models.ItemCreatedResponse) *AddEventCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add event created response +func (o *AddEventCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddEventCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// AddEventBadRequestCode is the HTTP code returned for type AddEventBadRequest +const AddEventBadRequestCode int = 400 + +/*AddEventBadRequest Invalid input, object invalid + +swagger:response addEventBadRequest +*/ +type AddEventBadRequest struct { +} + +// NewAddEventBadRequest creates AddEventBadRequest with default headers values +func NewAddEventBadRequest() *AddEventBadRequest { + + return &AddEventBadRequest{} +} + +// WriteResponse to the client +func (o *AddEventBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// AddEventInternalServerErrorCode is the HTTP code returned for type AddEventInternalServerError +const AddEventInternalServerErrorCode int = 500 + +/*AddEventInternalServerError Something unexpected happend, error raised + +swagger:response addEventInternalServerError +*/ +type AddEventInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewAddEventInternalServerError creates AddEventInternalServerError with default headers values +func NewAddEventInternalServerError() *AddEventInternalServerError { + + return &AddEventInternalServerError{} +} + +// WithPayload adds the payload to the add event internal server error response +func (o *AddEventInternalServerError) WithPayload(payload *models.ErrorResponse) *AddEventInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the add event internal server error response +func (o *AddEventInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *AddEventInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/event_management/add_event_urlbuilder.go b/services/eventsengine/restapi/operations/event_management/add_event_urlbuilder.go new file mode 100644 index 0000000..2152412 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/add_event_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// AddEventURL generates an URL for the add event operation +type AddEventURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddEventURL) WithBasePath(bp string) *AddEventURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *AddEventURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *AddEventURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/event" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *AddEventURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *AddEventURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *AddEventURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on AddEventURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on AddEventURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *AddEventURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/event_management/get_history.go b/services/eventsengine/restapi/operations/event_management/get_history.go new file mode 100644 index 0000000..bbaacc0 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_history.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetHistoryHandlerFunc turns a function with the right signature into a get history handler +type GetHistoryHandlerFunc func(GetHistoryParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetHistoryHandlerFunc) Handle(params GetHistoryParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetHistoryHandler interface for that can handle valid get history params +type GetHistoryHandler interface { + Handle(GetHistoryParams, interface{}) middleware.Responder +} + +// NewGetHistory creates a new http.Handler for the get history operation +func NewGetHistory(ctx *middleware.Context, handler GetHistoryHandler) *GetHistory { + return &GetHistory{Context: ctx, Handler: handler} +} + +/*GetHistory swagger:route GET /event/history/{account} eventManagement getHistory + +Provides the events for the id provided + +*/ +type GetHistory struct { + Context *middleware.Context + Handler GetHistoryHandler +} + +func (o *GetHistory) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetHistoryParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/event_management/get_history_parameters.go b/services/eventsengine/restapi/operations/event_management/get_history_parameters.go new file mode 100644 index 0000000..676e968 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_history_parameters.go @@ -0,0 +1,192 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetHistoryParams creates a new GetHistoryParams object +// no default values defined in spec. +func NewGetHistoryParams() GetHistoryParams { + + return GetHistoryParams{} +} + +// GetHistoryParams contains all the bound params for the get history operation +// typically these are obtained from a http.Request +// +// swagger:parameters getHistory +type GetHistoryParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be checked + Required: true + In: path + */ + Account string + /*Datetime from which to get the usage report + In: query + */ + From *int64 + /*Resource region to filter the usage + In: query + */ + Region *string + /*Resource type to filter the usage + In: query + */ + Resource *string + /*Datetime until which to get the usage report + In: query + */ + To *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetHistoryParams() beforehand. +func (o *GetHistoryParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + rAccount, rhkAccount, _ := route.Params.GetOK("account") + if err := o.bindAccount(rAccount, rhkAccount, route.Formats); err != nil { + res = append(res, err) + } + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + qRegion, qhkRegion, _ := qs.GetOK("region") + if err := o.bindRegion(qRegion, qhkRegion, route.Formats); err != nil { + res = append(res, err) + } + + qResource, qhkResource, _ := qs.GetOK("resource") + if err := o.bindResource(qResource, qhkResource, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindAccount binds and validates parameter Account from path. +func (o *GetHistoryParams) bindAccount(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.Account = raw + + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetHistoryParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("from", "query", "int64", raw) + } + o.From = &value + + return nil +} + +// bindRegion binds and validates parameter Region from query. +func (o *GetHistoryParams) bindRegion(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Region = &raw + + return nil +} + +// bindResource binds and validates parameter Resource from query. +func (o *GetHistoryParams) bindResource(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Resource = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetHistoryParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("to", "query", "int64", raw) + } + o.To = &value + + return nil +} diff --git a/services/eventsengine/restapi/operations/event_management/get_history_responses.go b/services/eventsengine/restapi/operations/event_management/get_history_responses.go new file mode 100644 index 0000000..0576f57 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_history_responses.go @@ -0,0 +1,149 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetHistoryOKCode is the HTTP code returned for type GetHistoryOK +const GetHistoryOKCode int = 200 + +/*GetHistoryOK Description of a successfully operation + +swagger:response getHistoryOK +*/ +type GetHistoryOK struct { + + /* + In: Body + */ + Payload []*models.Event `json:"body,omitempty"` +} + +// NewGetHistoryOK creates GetHistoryOK with default headers values +func NewGetHistoryOK() *GetHistoryOK { + + return &GetHistoryOK{} +} + +// WithPayload adds the payload to the get history o k response +func (o *GetHistoryOK) WithPayload(payload []*models.Event) *GetHistoryOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get history o k response +func (o *GetHistoryOK) SetPayload(payload []*models.Event) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHistoryOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Event, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetHistoryNotFoundCode is the HTTP code returned for type GetHistoryNotFound +const GetHistoryNotFoundCode int = 404 + +/*GetHistoryNotFound Item not found in the system + +swagger:response getHistoryNotFound +*/ +type GetHistoryNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetHistoryNotFound creates GetHistoryNotFound with default headers values +func NewGetHistoryNotFound() *GetHistoryNotFound { + + return &GetHistoryNotFound{} +} + +// WithPayload adds the payload to the get history not found response +func (o *GetHistoryNotFound) WithPayload(payload *models.ErrorResponse) *GetHistoryNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get history not found response +func (o *GetHistoryNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHistoryNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetHistoryInternalServerErrorCode is the HTTP code returned for type GetHistoryInternalServerError +const GetHistoryInternalServerErrorCode int = 500 + +/*GetHistoryInternalServerError Something unexpected happend, error raised + +swagger:response getHistoryInternalServerError +*/ +type GetHistoryInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetHistoryInternalServerError creates GetHistoryInternalServerError with default headers values +func NewGetHistoryInternalServerError() *GetHistoryInternalServerError { + + return &GetHistoryInternalServerError{} +} + +// WithPayload adds the payload to the get history internal server error response +func (o *GetHistoryInternalServerError) WithPayload(payload *models.ErrorResponse) *GetHistoryInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get history internal server error response +func (o *GetHistoryInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetHistoryInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/event_management/get_history_urlbuilder.go b/services/eventsengine/restapi/operations/event_management/get_history_urlbuilder.go new file mode 100644 index 0000000..9e04191 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_history_urlbuilder.go @@ -0,0 +1,142 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// GetHistoryURL generates an URL for the get history operation +type GetHistoryURL struct { + Account string + + From *int64 + Region *string + Resource *string + To *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHistoryURL) WithBasePath(bp string) *GetHistoryURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetHistoryURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetHistoryURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/event/history/{account}" + + account := o.Account + if account != "" { + _path = strings.Replace(_path, "{account}", account, -1) + } else { + return nil, errors.New("account is required on GetHistoryURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = swag.FormatInt64(*o.From) + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var regionQ string + if o.Region != nil { + regionQ = *o.Region + } + if regionQ != "" { + qs.Set("region", regionQ) + } + + var resourceQ string + if o.Resource != nil { + resourceQ = *o.Resource + } + if resourceQ != "" { + qs.Set("resource", resourceQ) + } + + var toQ string + if o.To != nil { + toQ = swag.FormatInt64(*o.To) + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetHistoryURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetHistoryURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetHistoryURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetHistoryURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetHistoryURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetHistoryURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/event_management/get_state.go b/services/eventsengine/restapi/operations/event_management/get_state.go new file mode 100644 index 0000000..daf033f --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_state.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStateHandlerFunc turns a function with the right signature into a get state handler +type GetStateHandlerFunc func(GetStateParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStateHandlerFunc) Handle(params GetStateParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStateHandler interface for that can handle valid get state params +type GetStateHandler interface { + Handle(GetStateParams, interface{}) middleware.Responder +} + +// NewGetState creates a new http.Handler for the get state operation +func NewGetState(ctx *middleware.Context, handler GetStateHandler) *GetState { + return &GetState{Context: ctx, Handler: handler} +} + +/*GetState swagger:route GET /event/status/{account} eventManagement getState + +Provides the events for the id provided + +*/ +type GetState struct { + Context *middleware.Context + Handler GetStateHandler +} + +func (o *GetState) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStateParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/event_management/get_state_parameters.go b/services/eventsengine/restapi/operations/event_management/get_state_parameters.go new file mode 100644 index 0000000..a952d9d --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_state_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetStateParams creates a new GetStateParams object +// no default values defined in spec. +func NewGetStateParams() GetStateParams { + + return GetStateParams{} +} + +// GetStateParams contains all the bound params for the get state operation +// typically these are obtained from a http.Request +// +// swagger:parameters getState +type GetStateParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the account to be checked + Required: true + In: path + */ + Account string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStateParams() beforehand. +func (o *GetStateParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rAccount, rhkAccount, _ := route.Params.GetOK("account") + if err := o.bindAccount(rAccount, rhkAccount, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindAccount binds and validates parameter Account from path. +func (o *GetStateParams) bindAccount(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.Account = raw + + return nil +} diff --git a/services/eventsengine/restapi/operations/event_management/get_state_responses.go b/services/eventsengine/restapi/operations/event_management/get_state_responses.go new file mode 100644 index 0000000..3e327d3 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_state_responses.go @@ -0,0 +1,149 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetStateOKCode is the HTTP code returned for type GetStateOK +const GetStateOKCode int = 200 + +/*GetStateOK Description of a successfully operation + +swagger:response getStateOK +*/ +type GetStateOK struct { + + /* + In: Body + */ + Payload []*models.State `json:"body,omitempty"` +} + +// NewGetStateOK creates GetStateOK with default headers values +func NewGetStateOK() *GetStateOK { + + return &GetStateOK{} +} + +// WithPayload adds the payload to the get state o k response +func (o *GetStateOK) WithPayload(payload []*models.State) *GetStateOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get state o k response +func (o *GetStateOK) SetPayload(payload []*models.State) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStateOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.State, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetStateNotFoundCode is the HTTP code returned for type GetStateNotFound +const GetStateNotFoundCode int = 404 + +/*GetStateNotFound Item not found in the system + +swagger:response getStateNotFound +*/ +type GetStateNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStateNotFound creates GetStateNotFound with default headers values +func NewGetStateNotFound() *GetStateNotFound { + + return &GetStateNotFound{} +} + +// WithPayload adds the payload to the get state not found response +func (o *GetStateNotFound) WithPayload(payload *models.ErrorResponse) *GetStateNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get state not found response +func (o *GetStateNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStateNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStateInternalServerErrorCode is the HTTP code returned for type GetStateInternalServerError +const GetStateInternalServerErrorCode int = 500 + +/*GetStateInternalServerError Something unexpected happend, error raised + +swagger:response getStateInternalServerError +*/ +type GetStateInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStateInternalServerError creates GetStateInternalServerError with default headers values +func NewGetStateInternalServerError() *GetStateInternalServerError { + + return &GetStateInternalServerError{} +} + +// WithPayload adds the payload to the get state internal server error response +func (o *GetStateInternalServerError) WithPayload(payload *models.ErrorResponse) *GetStateInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get state internal server error response +func (o *GetStateInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStateInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/event_management/get_state_urlbuilder.go b/services/eventsengine/restapi/operations/event_management/get_state_urlbuilder.go new file mode 100644 index 0000000..be5597a --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/get_state_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStateURL generates an URL for the get state operation +type GetStateURL struct { + Account string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStateURL) WithBasePath(bp string) *GetStateURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStateURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStateURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/event/status/{account}" + + account := o.Account + if account != "" { + _path = strings.Replace(_path, "{account}", account, -1) + } else { + return nil, errors.New("account is required on GetStateURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStateURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStateURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStateURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStateURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStateURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStateURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/event_management/list_states.go b/services/eventsengine/restapi/operations/event_management/list_states.go new file mode 100644 index 0000000..b7b9099 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/list_states.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListStatesHandlerFunc turns a function with the right signature into a list states handler +type ListStatesHandlerFunc func(ListStatesParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListStatesHandlerFunc) Handle(params ListStatesParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListStatesHandler interface for that can handle valid list states params +type ListStatesHandler interface { + Handle(ListStatesParams, interface{}) middleware.Responder +} + +// NewListStates creates a new http.Handler for the list states operation +func NewListStates(ctx *middleware.Context, handler ListStatesHandler) *ListStates { + return &ListStates{Context: ctx, Handler: handler} +} + +/*ListStates swagger:route GET /event/status eventManagement listStates + +Provides the list of states in not terminated state + +*/ +type ListStates struct { + Context *middleware.Context + Handler ListStatesHandler +} + +func (o *ListStates) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListStatesParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/event_management/list_states_parameters.go b/services/eventsengine/restapi/operations/event_management/list_states_parameters.go new file mode 100644 index 0000000..ef07383 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/list_states_parameters.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewListStatesParams creates a new ListStatesParams object +// no default values defined in spec. +func NewListStatesParams() ListStatesParams { + + return ListStatesParams{} +} + +// ListStatesParams contains all the bound params for the list states operation +// typically these are obtained from a http.Request +// +// swagger:parameters listStates +type ListStatesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Resource region to filter the usage + In: query + */ + Region *string + /*Resource type to filter the usage + In: query + */ + Resource *string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListStatesParams() beforehand. +func (o *ListStatesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qRegion, qhkRegion, _ := qs.GetOK("region") + if err := o.bindRegion(qRegion, qhkRegion, route.Formats); err != nil { + res = append(res, err) + } + + qResource, qhkResource, _ := qs.GetOK("resource") + if err := o.bindResource(qResource, qhkResource, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindRegion binds and validates parameter Region from query. +func (o *ListStatesParams) bindRegion(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Region = &raw + + return nil +} + +// bindResource binds and validates parameter Resource from query. +func (o *ListStatesParams) bindResource(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Resource = &raw + + return nil +} diff --git a/services/eventsengine/restapi/operations/event_management/list_states_responses.go b/services/eventsengine/restapi/operations/event_management/list_states_responses.go new file mode 100644 index 0000000..b075695 --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/list_states_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// ListStatesOKCode is the HTTP code returned for type ListStatesOK +const ListStatesOKCode int = 200 + +/*ListStatesOK Description of a successfully operation + +swagger:response listStatesOK +*/ +type ListStatesOK struct { + + /* + In: Body + */ + Payload []*models.MinimalState `json:"body,omitempty"` +} + +// NewListStatesOK creates ListStatesOK with default headers values +func NewListStatesOK() *ListStatesOK { + + return &ListStatesOK{} +} + +// WithPayload adds the payload to the list states o k response +func (o *ListStatesOK) WithPayload(payload []*models.MinimalState) *ListStatesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list states o k response +func (o *ListStatesOK) SetPayload(payload []*models.MinimalState) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListStatesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.MinimalState, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListStatesInternalServerErrorCode is the HTTP code returned for type ListStatesInternalServerError +const ListStatesInternalServerErrorCode int = 500 + +/*ListStatesInternalServerError Something unexpected happend, error raised + +swagger:response listStatesInternalServerError +*/ +type ListStatesInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListStatesInternalServerError creates ListStatesInternalServerError with default headers values +func NewListStatesInternalServerError() *ListStatesInternalServerError { + + return &ListStatesInternalServerError{} +} + +// WithPayload adds the payload to the list states internal server error response +func (o *ListStatesInternalServerError) WithPayload(payload *models.ErrorResponse) *ListStatesInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list states internal server error response +func (o *ListStatesInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListStatesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/event_management/list_states_urlbuilder.go b/services/eventsengine/restapi/operations/event_management/list_states_urlbuilder.go new file mode 100644 index 0000000..d5dad1b --- /dev/null +++ b/services/eventsengine/restapi/operations/event_management/list_states_urlbuilder.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package event_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListStatesURL generates an URL for the list states operation +type ListStatesURL struct { + Region *string + Resource *string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListStatesURL) WithBasePath(bp string) *ListStatesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListStatesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListStatesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/event/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var regionQ string + if o.Region != nil { + regionQ = *o.Region + } + if regionQ != "" { + qs.Set("region", regionQ) + } + + var resourceQ string + if o.Resource != nil { + resourceQ = *o.Resource + } + if resourceQ != "" { + qs.Set("resource", resourceQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListStatesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListStatesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListStatesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListStatesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListStatesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListStatesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/status_management/get_status.go b/services/eventsengine/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/status_management/get_status_parameters.go b/services/eventsengine/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..fd0ca82 --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the endpoint to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"status", "kafka-receiver", "kafka-sender", "trigger", "usage", "event"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/eventsengine/restapi/operations/status_management/get_status_responses.go b/services/eventsengine/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..4858f96 --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/status_management/get_status_urlbuilder.go b/services/eventsengine/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..151ece5 --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/status_management/show_status.go b/services/eventsengine/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/status_management/show_status_parameters.go b/services/eventsengine/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/restapi/operations/status_management/show_status_responses.go b/services/eventsengine/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..250d04d --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// ShowStatusInternalServerErrorCode is the HTTP code returned for type ShowStatusInternalServerError +const ShowStatusInternalServerErrorCode int = 500 + +/*ShowStatusInternalServerError Something unexpected happend, error raised + +swagger:response showStatusInternalServerError +*/ +type ShowStatusInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewShowStatusInternalServerError creates ShowStatusInternalServerError with default headers values +func NewShowStatusInternalServerError() *ShowStatusInternalServerError { + + return &ShowStatusInternalServerError{} +} + +// WithPayload adds the payload to the show status internal server error response +func (o *ShowStatusInternalServerError) WithPayload(payload *models.ErrorResponse) *ShowStatusInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status internal server error response +func (o *ShowStatusInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/status_management/show_status_urlbuilder.go b/services/eventsengine/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..6efc165 --- /dev/null +++ b/services/eventsengine/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/trigger_management/exec_sample.go b/services/eventsengine/restapi/operations/trigger_management/exec_sample.go new file mode 100644 index 0000000..3a21c8a --- /dev/null +++ b/services/eventsengine/restapi/operations/trigger_management/exec_sample.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ExecSampleHandlerFunc turns a function with the right signature into a exec sample handler +type ExecSampleHandlerFunc func(ExecSampleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ExecSampleHandlerFunc) Handle(params ExecSampleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ExecSampleHandler interface for that can handle valid exec sample params +type ExecSampleHandler interface { + Handle(ExecSampleParams, interface{}) middleware.Responder +} + +// NewExecSample creates a new http.Handler for the exec sample operation +func NewExecSample(ctx *middleware.Context, handler ExecSampleHandler) *ExecSample { + return &ExecSample{Context: ctx, Handler: handler} +} + +/*ExecSample swagger:route GET /trigger/sample triggerManagement execSample + +Sample task trigger + +*/ +type ExecSample struct { + Context *middleware.Context + Handler ExecSampleHandler +} + +func (o *ExecSample) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewExecSampleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/trigger_management/exec_sample_parameters.go b/services/eventsengine/restapi/operations/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..e3aad65 --- /dev/null +++ b/services/eventsengine/restapi/operations/trigger_management/exec_sample_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// no default values defined in spec. +func NewExecSampleParams() ExecSampleParams { + + return ExecSampleParams{} +} + +// ExecSampleParams contains all the bound params for the exec sample operation +// typically these are obtained from a http.Request +// +// swagger:parameters execSample +type ExecSampleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewExecSampleParams() beforehand. +func (o *ExecSampleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/eventsengine/restapi/operations/trigger_management/exec_sample_responses.go b/services/eventsengine/restapi/operations/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..a1df560 --- /dev/null +++ b/services/eventsengine/restapi/operations/trigger_management/exec_sample_responses.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// ExecSampleOKCode is the HTTP code returned for type ExecSampleOK +const ExecSampleOKCode int = 200 + +/*ExecSampleOK Sample task executed successfully + +swagger:response execSampleOK +*/ +type ExecSampleOK struct { +} + +// NewExecSampleOK creates ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + + return &ExecSampleOK{} +} + +// WriteResponse to the client +func (o *ExecSampleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// ExecSampleInternalServerErrorCode is the HTTP code returned for type ExecSampleInternalServerError +const ExecSampleInternalServerErrorCode int = 500 + +/*ExecSampleInternalServerError Something unexpected happend, error raised + +swagger:response execSampleInternalServerError +*/ +type ExecSampleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewExecSampleInternalServerError creates ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + + return &ExecSampleInternalServerError{} +} + +// WithPayload adds the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) WithPayload(payload *models.ErrorResponse) *ExecSampleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ExecSampleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/trigger_management/exec_sample_urlbuilder.go b/services/eventsengine/restapi/operations/trigger_management/exec_sample_urlbuilder.go new file mode 100644 index 0000000..33b621a --- /dev/null +++ b/services/eventsengine/restapi/operations/trigger_management/exec_sample_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ExecSampleURL generates an URL for the exec sample operation +type ExecSampleURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) WithBasePath(bp string) *ExecSampleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ExecSampleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/sample" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ExecSampleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ExecSampleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ExecSampleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ExecSampleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ExecSampleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ExecSampleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_system_usage.go b/services/eventsengine/restapi/operations/usage_management/get_system_usage.go new file mode 100644 index 0000000..9d00b8d --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_system_usage.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetSystemUsageHandlerFunc turns a function with the right signature into a get system usage handler +type GetSystemUsageHandlerFunc func(GetSystemUsageParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetSystemUsageHandlerFunc) Handle(params GetSystemUsageParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetSystemUsageHandler interface for that can handle valid get system usage params +type GetSystemUsageHandler interface { + Handle(GetSystemUsageParams, interface{}) middleware.Responder +} + +// NewGetSystemUsage creates a new http.Handler for the get system usage operation +func NewGetSystemUsage(ctx *middleware.Context, handler GetSystemUsageHandler) *GetSystemUsage { + return &GetSystemUsage{Context: ctx, Handler: handler} +} + +/*GetSystemUsage swagger:route GET /usage usageManagement getSystemUsage + +Generates an aggregated response by account of the usage recorded in the system during the time-window specified + +*/ +type GetSystemUsage struct { + Context *middleware.Context + Handler GetSystemUsageHandler +} + +func (o *GetSystemUsage) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetSystemUsageParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_system_usage_parameters.go b/services/eventsengine/restapi/operations/usage_management/get_system_usage_parameters.go new file mode 100644 index 0000000..223e089 --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_system_usage_parameters.go @@ -0,0 +1,167 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetSystemUsageParams creates a new GetSystemUsageParams object +// no default values defined in spec. +func NewGetSystemUsageParams() GetSystemUsageParams { + + return GetSystemUsageParams{} +} + +// GetSystemUsageParams contains all the bound params for the get system usage operation +// typically these are obtained from a http.Request +// +// swagger:parameters getSystemUsage +type GetSystemUsageParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to get the usage report + In: query + */ + From *int64 + /*Resource region to filter the usage + In: query + */ + Region *string + /*Resource type to filter the usage + In: query + */ + Resource *string + /*Datetime until which to get the usage report + In: query + */ + To *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetSystemUsageParams() beforehand. +func (o *GetSystemUsageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + qRegion, qhkRegion, _ := qs.GetOK("region") + if err := o.bindRegion(qRegion, qhkRegion, route.Formats); err != nil { + res = append(res, err) + } + + qResource, qhkResource, _ := qs.GetOK("resource") + if err := o.bindResource(qResource, qhkResource, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetSystemUsageParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("from", "query", "int64", raw) + } + o.From = &value + + return nil +} + +// bindRegion binds and validates parameter Region from query. +func (o *GetSystemUsageParams) bindRegion(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Region = &raw + + return nil +} + +// bindResource binds and validates parameter Resource from query. +func (o *GetSystemUsageParams) bindResource(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Resource = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetSystemUsageParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("to", "query", "int64", raw) + } + o.To = &value + + return nil +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_system_usage_responses.go b/services/eventsengine/restapi/operations/usage_management/get_system_usage_responses.go new file mode 100644 index 0000000..aa57f08 --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_system_usage_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetSystemUsageOKCode is the HTTP code returned for type GetSystemUsageOK +const GetSystemUsageOKCode int = 200 + +/*GetSystemUsageOK Description of a successfully operation + +swagger:response getSystemUsageOK +*/ +type GetSystemUsageOK struct { + + /* + In: Body + */ + Payload []*models.Usage `json:"body,omitempty"` +} + +// NewGetSystemUsageOK creates GetSystemUsageOK with default headers values +func NewGetSystemUsageOK() *GetSystemUsageOK { + + return &GetSystemUsageOK{} +} + +// WithPayload adds the payload to the get system usage o k response +func (o *GetSystemUsageOK) WithPayload(payload []*models.Usage) *GetSystemUsageOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get system usage o k response +func (o *GetSystemUsageOK) SetPayload(payload []*models.Usage) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSystemUsageOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Usage, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetSystemUsageInternalServerErrorCode is the HTTP code returned for type GetSystemUsageInternalServerError +const GetSystemUsageInternalServerErrorCode int = 500 + +/*GetSystemUsageInternalServerError Something unexpected happend, error raised + +swagger:response getSystemUsageInternalServerError +*/ +type GetSystemUsageInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSystemUsageInternalServerError creates GetSystemUsageInternalServerError with default headers values +func NewGetSystemUsageInternalServerError() *GetSystemUsageInternalServerError { + + return &GetSystemUsageInternalServerError{} +} + +// WithPayload adds the payload to the get system usage internal server error response +func (o *GetSystemUsageInternalServerError) WithPayload(payload *models.ErrorResponse) *GetSystemUsageInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get system usage internal server error response +func (o *GetSystemUsageInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSystemUsageInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_system_usage_urlbuilder.go b/services/eventsengine/restapi/operations/usage_management/get_system_usage_urlbuilder.go new file mode 100644 index 0000000..29f9dea --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_system_usage_urlbuilder.go @@ -0,0 +1,132 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/swag" +) + +// GetSystemUsageURL generates an URL for the get system usage operation +type GetSystemUsageURL struct { + From *int64 + Region *string + Resource *string + To *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSystemUsageURL) WithBasePath(bp string) *GetSystemUsageURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSystemUsageURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetSystemUsageURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/usage" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = swag.FormatInt64(*o.From) + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var regionQ string + if o.Region != nil { + regionQ = *o.Region + } + if regionQ != "" { + qs.Set("region", regionQ) + } + + var resourceQ string + if o.Resource != nil { + resourceQ = *o.Resource + } + if resourceQ != "" { + qs.Set("resource", resourceQ) + } + + var toQ string + if o.To != nil { + toQ = swag.FormatInt64(*o.To) + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetSystemUsageURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetSystemUsageURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetSystemUsageURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetSystemUsageURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetSystemUsageURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetSystemUsageURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_usage.go b/services/eventsengine/restapi/operations/usage_management/get_usage.go new file mode 100644 index 0000000..ec51547 --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_usage.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetUsageHandlerFunc turns a function with the right signature into a get usage handler +type GetUsageHandlerFunc func(GetUsageParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetUsageHandlerFunc) Handle(params GetUsageParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetUsageHandler interface for that can handle valid get usage params +type GetUsageHandler interface { + Handle(GetUsageParams, interface{}) middleware.Responder +} + +// NewGetUsage creates a new http.Handler for the get usage operation +func NewGetUsage(ctx *middleware.Context, handler GetUsageHandler) *GetUsage { + return &GetUsage{Context: ctx, Handler: handler} +} + +/*GetUsage swagger:route GET /usage/{id} usageManagement getUsage + +Generates an aggregated response of the usage recorded in the system during the time-window specified for the selected account + +*/ +type GetUsage struct { + Context *middleware.Context + Handler GetUsageHandler +} + +func (o *GetUsage) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetUsageParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_usage_parameters.go b/services/eventsengine/restapi/operations/usage_management/get_usage_parameters.go new file mode 100644 index 0000000..abde411 --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_usage_parameters.go @@ -0,0 +1,192 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetUsageParams creates a new GetUsageParams object +// no default values defined in spec. +func NewGetUsageParams() GetUsageParams { + + return GetUsageParams{} +} + +// GetUsageParams contains all the bound params for the get usage operation +// typically these are obtained from a http.Request +// +// swagger:parameters getUsage +type GetUsageParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to get the usage report + In: query + */ + From *int64 + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Resource region to filter the usage + In: query + */ + Region *string + /*Resource type to filter the usage + In: query + */ + Resource *string + /*Datetime until which to get the usage report + In: query + */ + To *int64 +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetUsageParams() beforehand. +func (o *GetUsageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qRegion, qhkRegion, _ := qs.GetOK("region") + if err := o.bindRegion(qRegion, qhkRegion, route.Formats); err != nil { + res = append(res, err) + } + + qResource, qhkResource, _ := qs.GetOK("resource") + if err := o.bindResource(qResource, qhkResource, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetUsageParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("from", "query", "int64", raw) + } + o.From = &value + + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetUsageParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindRegion binds and validates parameter Region from query. +func (o *GetUsageParams) bindRegion(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Region = &raw + + return nil +} + +// bindResource binds and validates parameter Resource from query. +func (o *GetUsageParams) bindResource(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Resource = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetUsageParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertInt64(raw) + if err != nil { + return errors.InvalidType("to", "query", "int64", raw) + } + o.To = &value + + return nil +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_usage_responses.go b/services/eventsengine/restapi/operations/usage_management/get_usage_responses.go new file mode 100644 index 0000000..d245419 --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_usage_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" +) + +// GetUsageOKCode is the HTTP code returned for type GetUsageOK +const GetUsageOKCode int = 200 + +/*GetUsageOK Description of a successfully operation + +swagger:response getUsageOK +*/ +type GetUsageOK struct { + + /* + In: Body + */ + Payload *models.Usage `json:"body,omitempty"` +} + +// NewGetUsageOK creates GetUsageOK with default headers values +func NewGetUsageOK() *GetUsageOK { + + return &GetUsageOK{} +} + +// WithPayload adds the payload to the get usage o k response +func (o *GetUsageOK) WithPayload(payload *models.Usage) *GetUsageOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage o k response +func (o *GetUsageOK) SetPayload(payload *models.Usage) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetUsageNotFoundCode is the HTTP code returned for type GetUsageNotFound +const GetUsageNotFoundCode int = 404 + +/*GetUsageNotFound Item not found in the system + +swagger:response getUsageNotFound +*/ +type GetUsageNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetUsageNotFound creates GetUsageNotFound with default headers values +func NewGetUsageNotFound() *GetUsageNotFound { + + return &GetUsageNotFound{} +} + +// WithPayload adds the payload to the get usage not found response +func (o *GetUsageNotFound) WithPayload(payload *models.ErrorResponse) *GetUsageNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage not found response +func (o *GetUsageNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetUsageInternalServerErrorCode is the HTTP code returned for type GetUsageInternalServerError +const GetUsageInternalServerErrorCode int = 500 + +/*GetUsageInternalServerError Something unexpected happend, error raised + +swagger:response getUsageInternalServerError +*/ +type GetUsageInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetUsageInternalServerError creates GetUsageInternalServerError with default headers values +func NewGetUsageInternalServerError() *GetUsageInternalServerError { + + return &GetUsageInternalServerError{} +} + +// WithPayload adds the payload to the get usage internal server error response +func (o *GetUsageInternalServerError) WithPayload(payload *models.ErrorResponse) *GetUsageInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage internal server error response +func (o *GetUsageInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/eventsengine/restapi/operations/usage_management/get_usage_urlbuilder.go b/services/eventsengine/restapi/operations/usage_management/get_usage_urlbuilder.go new file mode 100644 index 0000000..edc63b2 --- /dev/null +++ b/services/eventsengine/restapi/operations/usage_management/get_usage_urlbuilder.go @@ -0,0 +1,142 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/swag" +) + +// GetUsageURL generates an URL for the get usage operation +type GetUsageURL struct { + ID string + + From *int64 + Region *string + Resource *string + To *int64 + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageURL) WithBasePath(bp string) *GetUsageURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetUsageURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/usage/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetUsageURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = swag.FormatInt64(*o.From) + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var regionQ string + if o.Region != nil { + regionQ = *o.Region + } + if regionQ != "" { + qs.Set("region", regionQ) + } + + var resourceQ string + if o.Resource != nil { + resourceQ = *o.Resource + } + if resourceQ != "" { + qs.Set("resource", resourceQ) + } + + var toQ string + if o.To != nil { + toQ = swag.FormatInt64(*o.To) + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetUsageURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetUsageURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetUsageURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetUsageURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetUsageURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetUsageURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/eventsengine/restapi/server.go b/services/eventsengine/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/services/eventsengine/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/services/eventsengine/run/cert.crt b/services/eventsengine/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/eventsengine/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/eventsengine/run/config.toml b/services/eventsengine/run/config.toml new file mode 100644 index 0000000..1bd9381 --- /dev/null +++ b/services/eventsengine/run/config.toml @@ -0,0 +1,89 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "23h" +DBName = "cyclops" +Host = "localhost" +Password = "pass1234" +Port = 5432 +# SSLMode = enable | disable +SSLMode = "disable" +UserName = "cyclops" + +[EVENTS] +Filters = [ "filter1", "filter2" ] + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +# "" for no file-logging +LogFile = "" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8000" +CDR = "cdr:8000" +CreditManager = "creditsystem:8000" +CustomerDB = "customerdb:8000" +EventsEngine = "eventsengine:8000" +PlanManager = "planmanager:8000" +UDR = "udr:8000" + +[KAFKA] +Brokers = [ "kafka1:9092", "kafka2:9092", "kafka3:9092" ] +CDRIn = [ "CDR" ] +CDROut = [ "Credit" ] +Credit-SystemIn = [ "Credit" ] +EventsEngineIn = [ "Events" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMin = 10e3 +SizeMax = 10e6 +UDRIn = [ "UDR" ] +UDROut = [ "CDR" ] + +[PLANS] +Default = "-1" +Education = "-2" + +[PROMETHEUS] +Host = "prometheus:9090" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + diff --git a/services/eventsengine/run/docker-compose.yml b/services/eventsengine/run/docker-compose.yml new file mode 100644 index 0000000..8a6e52e --- /dev/null +++ b/services/eventsengine/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: SERVICE:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/services/eventsengine/run/key.key b/services/eventsengine/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/eventsengine/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/eventsengine/server/config.go b/services/eventsengine/server/config.go new file mode 100644 index 0000000..4eb0cf9 --- /dev/null +++ b/services/eventsengine/server/config.go @@ -0,0 +1,223 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + DefaultPlans map[string]string + Prometheus prometheusConfig +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type planConfig struct { + Default string +} +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("database.cacheretention"), + DbName: viper.GetString("database.dbname"), + Host: viper.GetString("database.host"), + Password: viper.GetString("database.password"), + Port: viper.GetInt("database.port"), + SSLMode: viper.GetString("database.sslmode"), + Username: viper.GetString("database.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + DefaultPlans: viper.GetStringMapString("plans"), + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/services/eventsengine/server/dbManager/dbManager.go b/services/eventsengine/server/dbManager/dbManager.go new file mode 100644 index 0000000..b6db3b2 --- /dev/null +++ b/services/eventsengine/server/dbManager/dbManager.go @@ -0,0 +1,770 @@ +package dbManager + +import ( + "errors" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/remeh/sizedwaitgroup" + "gitlab.com/cyclops-utilities/datamodels" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK + + innerIncluded + lowerIncluded + notIncluded + outterIncluded + upperIncluded + + stateActive = "active" + stateError = "error" + stateInactive = "inactive" + stateSuspended = "suspended" + stateTerminated = "terminated" + + bigBang = int64(0) + endOfTime = int64(32503680000) +) + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// On it there is the following parameters: +// - connStr: strings with the connection information to the database +// - Db: a gorm.DB pointer to the db to invoke all the db methods +type DbParameter struct { + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec +} + +var ( + eeTime float64 + eeTotal float64 +) + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization +// Returns: +// - DbParameter: struct to interact with dbManager functionalities +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + } + + l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + dp.Db.AutoMigrate(tables...) + + l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + //dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NewScope(&models.TABLE).TableName() + "', 'TIMESCALE-ROW-INDEX');") + + return &dp + +} + +// AddEvent job is to register the new event on its corresponding resource state. +// Parameters: +// - event: a reference containing the new event in the resource. +// Returns: +// - e: error raised in case of problems +func (d *DbParameter) AddEvent(event models.Event) (e error) { + + l.Trace.Printf("[DB] Attempting to register a new in the resource [ %v ] from the account [ %v ].\n", event.ResourceID, event.Account) + + now := time.Now().UnixNano() + + var states []*models.State + var s, state models.State + + patternSearch := models.State{ + Account: event.Account, + ResourceID: event.ResourceID, + Region: event.Region, + } + + patternUpdate := models.State{ + TimeFrom: event.TimeFrom, + EventTime: event.EventTime, + LastEvent: func(s string) *string { return &s }(stateTerminated), + } + + s = patternSearch + s.MetaData = event.MetaData + + // First check is there's anything from same resourceid with different metadata, + // if so, terminate them all + if e = d.Db.Where(patternSearch).Not(models.State{ + MetaData: event.MetaData, + }).Not(models.State{ + LastEvent: func(s string) *string { return &s }(stateTerminated), + }).Find(&states).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while checking if the resource already has registered states in the system. Error: %v\n", e) + + } + + if len(states) != 0 { + + l.Debug.Printf("[DB] We found [ %v ] states linked to the resource [ %v ] proceeding to mark them as terminated...\n", len(states), event.ResourceID) + + if e = d.UpdateStates(states, patternUpdate); e != nil { + + l.Warning.Printf("[DB] Something went wrong while terminating the other states linked to the resource [ %v ]. Error: %v\n", event.ResourceID, e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "States updated"}).Add(float64(len(states))) + + } + + } + + // check if Status is the same + // if so, update the last time event field + // if diferent, copy actual state to history, then change state into new values from event + if r := d.Db.Where(&s).First(&state).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + l.Debug.Printf("[DB] The resource [ %v ] doesn't have a linked state in the system, proceeding to generate one...\n", event.ResourceID) + + s.ResourceName = event.ResourceName + s.TimeTo = endOfTime + s.TimeFrom = *event.EventTime + s.ResourceType = event.ResourceType + s.LastEvent = event.LastEvent + s.EventTime = event.EventTime + + if e = d.Db.Create(&s).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while trying to create the state. Error: %v\n", e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "States created"}).Inc() + + } + + } else { + + l.Debug.Printf("[DB] The resource [ %v ] seems to be already in the system with state [ %v ], proceeding to update its state...\n", event.ResourceID, *state.LastEvent) + + if *state.LastEvent == *event.LastEvent { + + if e = d.Db.Model(&state).Updates(models.State{ + EventTime: event.EventTime, + }).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while updating the state. Error: %v\n", e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "States updated"}).Inc() + + } + + } else { + + l.Debug.Printf("[DB] The resource [ %v ] seems to have a previous different state: [ %v ] -> [ %v ], proceeding to update it...\n", event.ResourceID, *state.LastEvent, *event.LastEvent) + + h := state + h.TimeTo = *event.EventTime + + if e = d.AddToHistory(h); e != nil { + + l.Warning.Printf("[DB] Something went wrong while saving in the history the previous state. Error: %v\n", e) + + } + + if e = d.Db.Model(&state).Updates(models.State{ + EventTime: event.EventTime, + LastEvent: event.LastEvent, + TimeFrom: *event.EventTime, + }).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while updating the state. Error: %v\n", e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "States updated"}).Inc() + + } + + } + + } + + eeTotal++ + eeTime += float64(time.Now().UnixNano() - now) + + d.Metrics["time"].With(prometheus.Labels{"type": "Events average registering time"}).Set(eeTime / eeTotal / float64(time.Millisecond)) + + d.Metrics["count"].With(prometheus.Labels{"type": "Total events processed"}).Inc() + + d.Metrics["count"].With(prometheus.Labels{"type": "Total " + event.ResourceType + " events processed"}).Inc() + + return + +} + +// AddToHistory job is to archive the provided state as a new event in the +// history of changes linked to the state provided. +// Parameters: +// - state: State to be archived as a new event in the history of changes of +// the State. +// Returns: +// - e: error raised in case of problems +func (d *DbParameter) AddToHistory(state models.State) (e error) { + + l.Trace.Printf("[DB] Attempting to add the event [ %v ] to the history of changes of the state. Account [ %v ], Resource [ %v ].\n", *state.LastEvent, state.Account, state.ResourceID) + + h := models.Event{ + Account: state.Account, + EventTime: state.EventTime, + LastEvent: state.LastEvent, + MetaData: state.MetaData, + Region: state.Region, + ResourceID: state.ResourceID, + ResourceName: state.ResourceName, + ResourceType: state.ResourceType, + TimeFrom: state.TimeFrom, + TimeTo: state.TimeTo, + } + + if e = d.Db.Create(&h).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while adding the event to the history of the state. Error: %v\n", e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "Histories updated"}).Inc() + + } + + return + +} + +// DatesWithin job is to check whether the analized time-window overlaps or not, +// reporting how this happens and how much overlapping exists. +// Parameters: +// - EventFrom: int representing the start of the interval for the event. +// - EventTp: int representing the end of the interval for the event. +// - TimeFrom: int representing the start of the time-window. +// - TimeTo: int representing the end of the time-window. +// Returns: +// - inc: const(int) representing the state of the time-window vs the interval. +// - diff: int representing the region of overlapping between both time-windows. +func (d *DbParameter) DatesWithin(EventFrom, EventTo, TimeFrom, TimeTo int64) (inc int, diff int64) { + + l.Trace.Printf("[DB] Attempting to match the time-window with the state/event time interval.\n") + + if EventTo <= TimeFrom { + + l.Debug.Printf("[DB] Time-window is before the time interval of the state/interval.\n") + + inc = notIncluded + + return + + } + + if EventFrom >= TimeTo { + + l.Debug.Printf("[DB] Time-window is after the time interval of the state/interval.\n") + + inc = notIncluded + + return + + } + + if EventFrom <= TimeFrom && TimeTo <= EventTo { + + l.Debug.Printf("[DB] Time-window is completely within the time interval of the state/interval.\n") + + // INNER Time Window + inc = innerIncluded + diff = TimeTo - TimeFrom + + return + + } + + if EventFrom <= TimeFrom && EventTo <= TimeTo { + + l.Debug.Printf("[DB] Time-window starts within the time interval of the state/interval and goes forward in the timeline.\n") + + // UPPER Time Window + inc = upperIncluded + diff = EventTo - TimeFrom + + return + + } + + if TimeFrom <= EventFrom && TimeTo <= EventTo { + + l.Debug.Printf("[DB] Time-window finished within the time interval of the state/interval and starts before it in the timeline.\n") + + // LOWER Time Window included + inc = lowerIncluded + diff = TimeTo - EventFrom + + return + + } + + if TimeFrom <= EventFrom && EventTo <= TimeTo { + + l.Debug.Printf("[DB] The time interval of the state/interval is within the time-windows (AKA starts and finish outside the interval).\n") + + // OUTTER Time Window + inc = outterIncluded + diff = EventTo - EventFrom + + return + } + + l.Warning.Printf("[DB] Time-window is from the 4th dimension, reach the administrator, the CERN, and the whole scientific community ASAP!\n") + inc = notIncluded + + return + +} + +// GetAllStates job is to retrieve a snapshot of all the states present in the +// system at the time of invokation- +// Returns: +// - slice of States containing all the resources state in the system +// - error raised in case of problems +func (d *DbParameter) GetAllStates() ([]*models.State, error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the states present in the system.\n") + + var s []*models.State + var e error + + if e := d.Db.Find(&s).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the states in the system. Error: %v\n", e) + + } + + return s, e + +} + +// GetState job is to retrieve the actual state of every resource linked to the +// provided account. +// Parameters: +// - ac: string representing the ID of the account to be processed. +// Returns: +// - slice of State containing the states kept in the system of the resources +// linked to the provided account +// - error raised in case of problems +func (d *DbParameter) GetState(ac string) ([]*models.State, error) { + + l.Trace.Printf("[DB] Attempting to get the actual state of the account [ %v ].\n", ac) + + var s []*models.State + var e error + + if e := d.Db.Where(&models.State{Account: ac}).Find(&s).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the state of the account [ %v ]. Error: %v\n", ac, e) + + } + + return s, e + +} + +// ListState job is to retrieve the list of not terminated states in the system +// for the requested region and resource type.. +// Parameters: +// - metric +// - region +// Returns: +// - slice of State containing the states kept in the system. +// - error raised in case of problems +func (d *DbParameter) ListState(metric, region string) ([]*models.MinimalState, error) { + + l.Trace.Printf("[DB] Attempting to get the list of not terminated [ %v ] states for region [ %v ].\n", metric, region) + + var s []*models.MinimalState + var e error + + filter := "terminated" + + if e := d.Db.Table("states").Where(&models.State{Region: region, ResourceType: metric}).Not(&models.State{LastEvent: &filter}).Order("account").Scan(&s).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the list of states from the system. Error: %v\n", e) + + } + + return s, e + +} + +// GetAllHistory job is to retrieve the complete history of changes in the state +// of the provided resource linked to the given account. +// Parameters: +// - ac: string representing the ID of the account to be processed. +// - u: Use reference used as the pattern to match the specific state needed. +// Returns: +// - slice of Event containing the changes in the history of the provided account. +// - error raised in case of problems +func (d *DbParameter) GetAllHistory(ac string, u models.Use) ([]*models.Event, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the full history of the resource [ %v ] from account [ %v ].\n", u.ResourceID, ac) + + var ev []*models.Event + var e error + + if e := d.Db.Where(&models.Event{ + Account: ac, + ResourceID: u.ResourceID, + ResourceName: u.ResourceName, + ResourceType: u.ResourceType, + MetaData: u.MetaData, + }).Find(&ev).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the history of the resource [ %v ]. Error: %v\n", u.ResourceID, e) + + } + + return ev, e + +} + +// GetHistory job is to retrieve the history of changes in the state of the +// provided account during the given time-window, with the posibility of filter +// the result by the type of resource. +// Parameters: +// - ac: string representing the ID of the account to be processed. +// - ty: string representing the resource type to use as filter +// - rg: string representing the resource region to use as filter +// - from: int representing the start of the time-window. +// - to: int representing the end of the time-window. +// Returns: +// - slice of Event containing the changes in the history of the provided account. +// - error raised in case of problems +func (d *DbParameter) GetHistory(ac, ty, rg string, from, to int64) ([]*models.Event, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the history of the account [ %v ].\n", ac) + + var ev []*models.Event + var e error + + whereString := d.Db.NamingStrategy.ColumnName("", "TimeFrom") + " >= ? AND " + d.Db.NamingStrategy.ColumnName("", "TimeTo") + " <= ?" + + if e := d.Db.Where(whereString, from, to).Where(&models.Event{ + Account: ac, + ResourceType: ty, + Region: rg, + }).Find(&ev).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the history of the account [ %v ]. Error: %v\n", ac, e) + + } + + return ev, e + +} + +// GetUsage job is to compute the usage accumulated by the provided account +// considering the time in the actual state and the history of changes that +// the account resources have had during the provided time-window, with the +// posibility of filtering by resource type. +// Parameters: +// - ac: string representing the ID of the account to be processed. +// - ty: string representing the resource type to use as filter +// - rg: string representing the resource region to use as filter +// - from: int representing the start of the time-window. +// - to: int representing the end of the time-window. +// Returns: +// - Usage reference containing the usage of the account in the system in the +// provided time-window. +// - error raised in case of problems +func (d *DbParameter) GetUsage(ac, ty, rg string, from, to int64) (*models.Usage, error) { + + l.Trace.Printf("[DB] Attempting to compute the usage of the account [ %v ].\n", ac) + + var u models.Usage + var e error + + // First we check if the actual State is in the time-window + states, e := d.GetState(ac) + + u.AccountID = ac + u.TimeFrom = from + u.TimeTo = to + + for i := range states { + + if ty != "" && states[i].ResourceType != ty { + + l.Trace.Printf("[DB] Resource filtering active. Resource [ %v ] not matching criteria [ %v ].\n", states[i].ResourceType, ty) + + continue + + } + + if rg != "" && states[i].Region != rg { + + l.Trace.Printf("[DB] Resource filtering active. Resource [ %v ] not matching criteria [ %v ].\n", states[i].ResourceType, rg) + + continue + + } + + var use models.Use + use.Region = states[i].Region + use.ResourceID = states[i].ResourceID + use.ResourceName = states[i].ResourceName + use.ResourceType = states[i].ResourceType + use.MetaData = states[i].MetaData + use.Unit = "seconds" + + usage := make(datamodels.JSONdb) + + usage[*states[i].LastEvent] = int64(0) + + // If it is, then we check is the time window goes before the actual state, + // if not, we create the usage and done + // If it does.. + + if inc, contrib := d.DatesWithin(states[i].TimeFrom, states[i].TimeTo, from, to); inc == innerIncluded || inc == upperIncluded { + + l.Trace.Printf("[DB] Resource [ %v ] state contained within the time-window, skipping history check.\n", states[i].ResourceID) + + usage[*states[i].LastEvent] = usage[*states[i].LastEvent].(int64) + contrib + + } else { + + if inc != notIncluded { + + l.Trace.Printf("[DB] Resource [ %v ] state not (fully) contained within the time-window, checking history of the resource.\n", states[i].ResourceID) + + usage[*states[i].LastEvent] = usage[*states[i].LastEvent].(int64) + contrib + + } + + // We get the History of the State, + // for each entry we check if the time-windows covers it, + // if so we add the contribution to the usage + // if not, we skip it + history, e := d.GetAllHistory(ac, use) + + if e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the resource [ %v ] history. Error: %v\n", states[i].ResourceID, e) + + } else { + + for id := range history { + + if included, contribution := d.DatesWithin(history[id].TimeFrom, history[id].TimeTo, from, to); included != notIncluded { + + if _, ok := usage[*history[id].LastEvent]; !ok { + + usage[*history[id].LastEvent] = int64(0) + + } + + l.Debug.Printf("[DB] Resource [ %v ] history register contained within the time-window.\n", states[i].ResourceID) + + usage[*history[id].LastEvent] = usage[*history[id].LastEvent].(int64) + contribution + + } + + } + + } + + } + + delete(usage, stateTerminated) + + for id := range usage { + + if usage[id].(int64) == int64(0) { + + delete(usage, id) + + } + + } + + if len(usage) != 0 { + + use.UsageBreakup = usage + + u.Usage = append(u.Usage, &use) + + } else { + + l.Warning.Printf("[DB] The resource [ %v ] has no data in the specified time-window, skipping it's usage report.\n", states[i].ResourceID) + + } + + } + + return &u, e + +} + +// GetSystemUsage job is to compute the usage accumulated in the whole system +// by account considering the time in the actual state and the history of changes +// that the account resources have had during the provided time-window, with the +// posibility of filtering by resource type. +// Parameters: +// - from: int representing the start of the time-window. +// - to: int representing the end of the time-window. +// - ty: string representing the resource type to use as filter +// - rg: string representing the resource region to use as filter +// Returns: +// - slice of Usages containing the usage per account in the system in the +// provided time-window. +// - error raised in case of problems +func (d *DbParameter) GetSystemUsage(from, to int64, ty, rg string) ([]*models.Usage, error) { + + l.Trace.Printf("[DB] Attempting to compute the system usage.\n") + + var u []*models.Usage + var e error + + ids := make(map[string]struct{}) + mutex := &sync.Mutex{} + + swg := sizedwaitgroup.New(8) + + if states, e := d.GetAllStates(); e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the states recorded in the system. Error: %v\n", e) + + } else { + + for index := range states { + + // Goroutines start + swg.Add() + go func(index int) { + + i := index + defer swg.Done() + + mutex.Lock() + _, exists := ids[states[i].Account] + mutex.Unlock() + + if exists { + + l.Trace.Printf("[DB] Account [ %v ] already processed, skipping...\n", states[i].Account) + + return + + } + + mutex.Lock() + ids[states[i].Account] = struct{}{} + mutex.Unlock() + + if su, e := d.GetUsage(states[i].Account, ty, rg, from, to); e != nil || su.Usage == nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the usage of the account [ %v ]. Error: %v\n", states[i].Account, e) + + } else { + + mutex.Lock() + u = append(u, su) + mutex.Unlock() + + } + + }(index) + + } + } + + swg.Wait() + + return u, e + +} + +// UpdateStates job is to process the provided states given a pattern, ranging +// through the given states, records the change in the history of the state and +// then updates the state with in the system according to the pattern. +// Parameters: +// - states: slice of State to be updated in the system. +// - pattern: a State reference containing the changes to be done previous to +// the update in the system. +// Returns: +// - error raised in case of problems +func (d *DbParameter) UpdateStates(states []*models.State, pattern models.State) error { + + l.Trace.Printf("[DB] Attempting to update [ %v ] states.\n", len(states)) + + var counth, countdb int = 0, 0 + var e error + + for i := range states { + + l.Debug.Printf("[DB] Processing state for resource [ %v ] from account [ %v ].\n", states[i].ResourceID, states[i].Account) + + s := states[i] + s.TimeTo = pattern.TimeFrom + + if e = d.AddToHistory(*s); e != nil { + + l.Warning.Printf("[DB] Something went wrong while saving the history of the state. Error: %v\n", e) + + counth++ + + } + + if e = d.Db.Model(states[i]).Updates(pattern).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while updating the state in the system. Error: %v\n", e) + + countdb++ + + } + + } + + l.Trace.Printf("[DB] Update of states finished with [ %v ] errors while saving the history and [ %v ] while updating the states\n", counth, countdb) + + return e + +} diff --git a/services/eventsengine/server/eventManager/eventManager.go b/services/eventsengine/server/eventManager/eventManager.go new file mode 100644 index 0000000..61c99e7 --- /dev/null +++ b/services/eventsengine/server/eventManager/eventManager.go @@ -0,0 +1,290 @@ +package eventManager + +import ( + "context" + "strings" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/event_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + bigBang = int64(0) + endOfTime = int64(32503680000) +) + +// EventManager is the struct defined to group and contain all the methods +// that interact with the events endpoints. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type EventManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager + filters []string +} + +// New is the function to create the struct EventManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// Returns: +// - EventManager: struct to interact with EventManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, filters []string) *EventManager { + + l.Trace.Printf("[EventManager] Generating new EventManager.\n") + + monit.InitEndpoint("event") + + return &EventManager{ + db: db, + monit: monit, + filters: filters, + } + +} + +// AddEvent (Swagger func) is the function behind the (POST) API Endpoint +// /event +// Its job is to include in the system the information given by the new event. +func (m *EventManager) AddEvent(ctx context.Context, params event_management.AddEventParams) middleware.Responder { + + l.Trace.Printf("[EventManager] AddEvent endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("event", callTime) + + for _, f := range m.filters { + + if f != "" && strings.Contains(params.Event.ResourceName, f) { + + l.Warning.Printf("Ignoring event: %v", params.Event.ResourceName) + + s := "Event resource is blacklisted, event ignored." + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/event"}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewAddEventInternalServerError().WithPayload(&errorReturn) + + } + + } + + e := m.db.AddEvent(*params.Event) + + if e != nil { + + s := "Error registering the event: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/event"}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewAddEventInternalServerError().WithPayload(&errorReturn) + + } + + createdReturn := models.ItemCreatedResponse{ + Message: "New Event registered in the system.", + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/event"}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewAddEventCreated().WithPayload(&createdReturn) + +} + +// GetState (Swagger func) is the function behind the (GET) API Endpoint +// /event/status/{id} +// Its job is to get the actual state of the provided account. +func (m *EventManager) GetState(ctx context.Context, params event_management.GetStateParams) middleware.Responder { + + l.Trace.Printf("[EventManager] GetState endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("event", callTime) + + state, e := m.db.GetState(params.Account) + + if e != nil { + + s := "Retrieval of the associated states failed: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/event/status/" + params.Account}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewGetStateInternalServerError().WithPayload(&errorReturn) + + } + + if state != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/event/status/" + params.Account}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewGetStateOK().WithPayload(state) + + } + + s := "The Account doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/event/status/" + params.Account}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewGetStateNotFound().WithPayload(&missingReturn) + +} + +// GetHistory (Swagger func) is the function behind the (GET) API Endpoint +// /event/history/{id} +// Its job is to provide the history of changes in the state of the provided +// account. +func (m *EventManager) GetHistory(ctx context.Context, params event_management.GetHistoryParams) middleware.Responder { + + l.Trace.Printf("[EventManager] GetHistory endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("event", callTime) + + ty, rg := string(""), string("") + from, to := bigBang, endOfTime + + if params.Resource != nil { + + ty = *params.Resource + + } + + if params.Region != nil { + + rg = *params.Region + + } + + if params.From != nil { + + from = *params.From + + } + + if params.To != nil { + + to = *params.To + + } + + history, e := m.db.GetHistory(params.Account, ty, rg, from, to) + + if e != nil { + + s := "Problem retrieving the history of the event: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/event/history/" + params.Account}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewGetHistoryInternalServerError().WithPayload(&errorReturn) + + } + + if history != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/event/history/" + params.Account}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewGetHistoryOK().WithPayload(history) + + } + + s := "The Usage doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/event/history/" + params.Account}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewGetHistoryNotFound().WithPayload(&missingReturn) + +} + +// ListState (Swagger func) is the function behind the (GET) API Endpoint +// /event/status +// Its job is to get the actual state of the provided account. +func (m *EventManager) ListStates(ctx context.Context, params event_management.ListStatesParams) middleware.Responder { + + l.Trace.Printf("[EventManager] ListState endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("event", callTime) + + var metric, region string + + if params.Resource != nil { + + metric = *params.Resource + + } + + if params.Region != nil { + + region = *params.Region + + } + + state, e := m.db.ListState(metric, region) + + if e != nil { + + s := "List of accounts states failed: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/event/status"}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewListStatesInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/event/status"}).Inc() + + m.monit.APIHitDone("event", callTime) + + return event_management.NewListStatesOK().WithPayload(state) + +} diff --git a/services/eventsengine/server/kafka.go b/services/eventsengine/server/kafka.go new file mode 100644 index 0000000..2c72cf6 --- /dev/null +++ b/services/eventsengine/server/kafka.go @@ -0,0 +1,311 @@ +package main + +import ( + "context" + "crypto/tls" + "reflect" + "strconv" + "time" + + "github.com/remeh/sizedwaitgroup" + "github.com/segmentio/encoding/json" + + "github.com/prometheus/client_golang/prometheus" + kafka "github.com/segmentio/kafka-go" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaFunction func(*dbManager.DbParameter, interface{}) error + +type kafkaHandlerConf struct { + in []kafkaPackage + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + model interface{} + function kafkaFunction + channel chan interface{} + saveDB bool +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(db *dbManager.DbParameter, monit *statusManager.StatusManager, kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.in != nil { + + monit.InitEndpoint("kafka-receiver") + + for _, p := range kH.in { + + go kafkaReceiver(db, monit, p.topic, p.partition, p.model, p.function, p.saveDB) + + } + } + + if kH.out != nil { + + monit.InitEndpoint("kafka-sender") + + for _, p := range kH.out { + + go kafkaSender(db, monit, p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaReceiver is the abstracted interface used to receive JSON data from kafka. +// The functions assumes that by default anything that comes from the kafka topic +// and validates against a specific data model has to be added to the db. +// Besides that it has the option to call an external function to interact with +// the data before putting it in the db. +// Parameters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - m: model to validate data against. +// - f: optional external function for more functionality. +// - saveDB: bool to control is the received data needs to be saved in the db. +func kafkaReceiver(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, m interface{}, f kafkaFunction, saveDB bool) { + + l.Trace.Printf("[KAFKA] Initializing kafka receiver for topic: %v.\n", t) + + conf := kafka.ReaderConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Partition: p, + MinBytes: cfg.Kafka.MinBytes, + MaxBytes: cfg.Kafka.MaxBytes, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + r := kafka.NewReader(conf) + defer r.Close() + + if e := r.SetOffset(cfg.Kafka.Offset); e != nil { + + l.Warning.Printf("[KAFKA] There was a problem when setting the offset, stopping the kafka handler NOW. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream offset"}).Inc() + + return + + } + + swg := sizedwaitgroup.New(8) + + for { + + rm, e := r.ReadMessage(context.Background()) + + if e != nil { + + l.Warning.Printf("[KAFKA] Error detected in the kafka stream. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream"}).Inc() + + continue + + } + + // Goroutines start + swg.Add() + go func() { + + callTime := time.Now() + monit.APIHit("kafka-receiver", callTime) + + defer swg.Done() + + o := reflect.New(reflect.TypeOf(m)).Interface() + + if e := json.Unmarshal(rm.Value, &o); e == nil { + + l.Info.Printf("[KAFKA] Relevant information detected in the stream: Topic: %v, partition: %v.\n", t, p) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object received"}).Inc() + + if f != nil { + + l.Info.Printf("[KAFKA] Function for specialized work detected. Starting its processing.\n") + + if err := f(db, o); err != nil { + + l.Warning.Printf("[KAFKA] There was a problem processing the model's specific function. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: linked function"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: linked function"}).Inc() + + } + + } + + if saveDB { + + l.Info.Printf("[KAFKA] Saving procesed record in the database.\n") + + if err := db.Db.Create(o).Error; err != nil { + + l.Warning.Printf("[KAFKA] There was a problem adding the record into the database. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: db saving"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object db saved"}).Inc() + + } + + } + + } else { + + l.Warning.Printf("[KAFKA] The information in the stream does not fit the expected model, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream-rubish"}).Inc() + + } + + monit.APIHitDone("kafka-receiver", callTime) + + }() + + } + +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + l.Info.Printf("[KAFKA] The channel has problems or has been closed.\n") + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: channel"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + callTime := time.Now() + monit.APIHit("kafka-sender", callTime) + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: stream"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "OK: object sent"}).Inc() + + } + + monit.APIHitDone("kafka-sender", callTime) + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: JSON Marshalling"}).Inc() + + } + + }() + + } + +} diff --git a/services/eventsengine/server/main.go b/services/eventsengine/server/main.go new file mode 100644 index 0000000..487cf56 --- /dev/null +++ b/services/eventsengine/server/main.go @@ -0,0 +1,176 @@ +package main + +import ( + "crypto/tls" + "github.com/segmentio/encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/services/eventsengine/server/metrics.go b/services/eventsengine/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/services/eventsengine/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/services/eventsengine/server/security.go b/services/eventsengine/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/services/eventsengine/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/services/eventsengine/server/service.go b/services/eventsengine/server/service.go new file mode 100644 index 0000000..aaa08cb --- /dev/null +++ b/services/eventsengine/server/service.go @@ -0,0 +1,130 @@ +package main + +import ( + "net/http" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/eventManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/statusManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/usageManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,...,N have to be customized + db := dbStart(&models.Event{}, &models.State{}) + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + // In case of needed, here is where kafka support is started + // The functions needs to be customized accordingly to the needs of the service + // And the parts of the service that might need to send messages need to get + // the channel + _ = kafkaStart(db, mon) + + //bp := getBasePath() + + // Parts of the service HERE + v := eventManager.New(db, mon, cfg.Events.Filters) + u := usageManager.New(db, mon) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + EventManagementAPI: v, + UsageManagementAPI: u, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Parameters: +// - db: DbPAramenter reference for interaction with the db. +// - mon: statusManager parameter reference to interact with the statusManager +// subsystem +// Returns: +// - ch: a interface{} channel to be able to send thing through the kafka topic generated. +func kafkaStart(db *dbManager.DbParameter, mon *statusManager.StatusManager) (ch chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + f := func(db *dbManager.DbParameter, model interface{}) (e error) { + + if e = db.AddEvent(*model.(*models.Event)); e != nil { + + l.Warning.Printf("[KAFKA] There was an error while apliying the linked function. Error: %v\n", e) + + } else { + + l.Trace.Printf("[KAFKA] Aplication of the linked function done succesfully.\n") + + } + return + + } + + ch = make(chan interface{}) + + handler := kafkaHandlerConf{ + in: []kafkaPackage{ + { + topic: cfg.Kafka.TopicsIn[0], + model: models.Event{}, + function: f, + saveDB: false, + }, + }, + } + + kafkaHandler(db, mon, handler) + + return + +} diff --git a/services/eventsengine/server/statusManager/statusManager.go b/services/eventsengine/server/statusManager/statusManager.go new file mode 100644 index 0000000..bc8bb14 --- /dev/null +++ b/services/eventsengine/server/statusManager/statusManager.go @@ -0,0 +1,325 @@ +package statusManager + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 + mutex *sync.Mutex +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + mutex = &sync.Mutex{} + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + avgTime[key] = t.UnixNano() + mutex.Unlock() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + previous, exists := avgTime[key] + mutex.Unlock() + + if exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + mutex.Lock() + delete(avgTime, key) + mutex.Unlock() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/services/eventsengine/server/triggerManager/triggerManager.go b/services/eventsengine/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..3df09dd --- /dev/null +++ b/services/eventsengine/server/triggerManager/triggerManager.go @@ -0,0 +1,72 @@ +package triggerManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// TriggerManager is the struct defined to group and contain all the methods +// that interact with the trigger subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type TriggerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +var returnValue models.ErrorResponse + +// New is the function to create the struct TriggerManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// Returns: +// - TriggerManager: struct to interact with triggerManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *TriggerManager { + + l.Trace.Printf("[Trigger] Generating new triggerManager.\n") + + monit.InitEndpoint("trigger") + + // Default return string in case something weird happens. + // It usually means that something went wrong in the dbManager. + s := "Something unexpected happened, check with the administrator." + + returnValue = models.ErrorResponse{ + ErrorString: &s, + } + + return &TriggerManager{ + db: db, + monit: monit, + } + +} + +// ExecSample (Swagger func) is the function behind the /trigger/sample endpoint. +// It is a dummy function for reference. +func (m *TriggerManager) ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder { + + l.Trace.Printf("[Trigger] ExecSample endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/trigger/sample"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecSampleOK() + +} diff --git a/services/eventsengine/server/usageManager/usageManager.go b/services/eventsengine/server/usageManager/usageManager.go new file mode 100644 index 0000000..be70d86 --- /dev/null +++ b/services/eventsengine/server/usageManager/usageManager.go @@ -0,0 +1,195 @@ +package usageManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/restapi/operations/usage_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + bigBang = int64(0) + endOfTime = int64(32503680000) +) + +// UsageManager is the struct defined to group and contain all the methods +// that interact with the usage endpoints. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type UsageManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct UsageManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// Returns: +// - UsageManager: struct to interact with UsageManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *UsageManager { + + l.Trace.Printf("[EventManager] Generating new EventManager.\n") + + monit.InitEndpoint("usage") + + return &UsageManager{ + db: db, + monit: monit, + } + +} + +// GetSystemUsage (Swagger func) is the function behind the (GET) API Endpoint +// /usage +// Its job is to get the usage of all the accounts in the system during the +// provided time-window with the posibility of filtering the results by the +// type of resource. +func (m *UsageManager) GetSystemUsage(ctx context.Context, params usage_management.GetSystemUsageParams) middleware.Responder { + + l.Trace.Printf("[UsageManager] GetSystemUsage endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("usage", callTime) + + from, to := bigBang, endOfTime + ty := string("") + rg := string("") + + if params.From != nil { + + from = *params.From + + } + + if params.To != nil { + + to = *params.To + + } + + if params.Resource != nil { + + ty = *params.Resource + + } + + if params.Region != nil { + + rg = *params.Region + + } + + use, e := m.db.GetSystemUsage(from, to, ty, rg) + + if e != nil { + + s := "Problem retrieving the usage: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/usage"}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetSystemUsageInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage"}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetSystemUsageOK().WithPayload(use) + +} + +// GetUsage (Swagger func) is the function behind the (GET) API Endpoint +// /usage/{id} +// Its job is to get the usage of the provided account in the system during the +// provided time-window with the posibility of filtering the results by the +// type of resource. +func (m *UsageManager) GetUsage(ctx context.Context, params usage_management.GetUsageParams) middleware.Responder { + + l.Trace.Printf("[UsageManager] GetUsage endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("usage", callTime) + + from, to := bigBang, endOfTime + ty := string("") + rg := string("") + + if params.From != nil { + + from = *params.From + + } + + if params.To != nil { + + to = *params.To + + } + + if params.Resource != nil { + + ty = *params.Resource + + } + + if params.Region != nil { + + rg = *params.Region + + } + + use, e := m.db.GetUsage(params.ID, ty, rg, from, to) + + if e != nil { + + s := "Problem retrieving the usage from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/usage/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageInternalServerError().WithPayload(&errorReturn) + + } + + if use != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageOK().WithPayload(use) + + } + + s := "The Usage doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/usage/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageNotFound().WithPayload(&missingReturn) + +} diff --git a/services/eventsengine/swagger.yaml b/services/eventsengine/swagger.yaml new file mode 100644 index 0000000..35a46c7 --- /dev/null +++ b/services/eventsengine/swagger.yaml @@ -0,0 +1,527 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v1.0" +info: + description: An API which supports creation, deletion, listing etc of Event Engine + version: "1.0.0" + title: Event Engine Management API + contact: + email: diego@cyclops-labs.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + - name: eventManagement + description: Actions relating to the adquisition of events in the system + - name: usageManagement + description: Actions relating to the reporting of the usages in the system + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - status + - kafka-receiver + - kafka-sender + - trigger + - usage + - event + required: true + description: Id of the endpoint to be checked + /trigger/sample: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Sample task trigger + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: execSample + responses: + '200': + description: Sample task executed successfully + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + + /event: + post: + tags: + - eventManagement + consumes: + - application/json + produces: + - application/json + summary: Takes into the system the provided event + security: + - Keycloak: [admin] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: addEvent + responses: + '201': + description: Item added successfully + schema: + $ref: "#/definitions/ItemCreatedResponse" + '400': + description: Invalid input, object invalid + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: event + in: body + description: Event to be added to the system + required: true + schema: + $ref: "#/definitions/Event" + /event/history/{account}: + get: + tags: + - eventManagement + produces: + - application/json + summary: Provides the events for the id provided + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getHistory + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Event" + '404': + description: Item not found in the system + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: account + in: path + description: Id of the account to be checked + required: true + type: string + - name: from + in: query + description: Datetime from which to get the usage report + type: integer + - name: to + in: query + description: Datetime until which to get the usage report + type: integer + - name: resource + in: query + description: Resource type to filter the usage + type: string + - name: region + in: query + description: Resource region to filter the usage + type: string + /event/status: + get: + tags: + - eventManagement + produces: + - application/json + summary: Provides the list of states in not terminated state + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: listStates + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/MinimalState" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: resource + in: query + description: Resource type to filter the usage + type: string + - name: region + in: query + description: Resource region to filter the usage + type: string + /event/status/{account}: + get: + tags: + - eventManagement + produces: + - application/json + summary: Provides the events for the id provided + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getState + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/State" + '404': + description: Item not found in the system + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: account + in: path + description: Id of the account to be checked + required: true + type: string + + /usage: + get: + tags: + - usageManagement + produces: + - application/json + summary: Generates an aggregated response by account of the usage recorded in the system during the time-window specified + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getSystemUsage + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Usage" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: from + in: query + description: Datetime from which to get the usage report + type: integer + - name: to + in: query + description: Datetime until which to get the usage report + type: integer + - name: resource + in: query + description: Resource type to filter the usage + type: string + - name: region + in: query + description: Resource region to filter the usage + type: string + /usage/{id}: + get: + tags: + - usageManagement + produces: + - application/json + summary: Generates an aggregated response of the usage recorded in the system during the time-window specified for the selected account + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getUsage + responses: + '200': + description: Description of a successfully operation + schema: + $ref: "#/definitions/Usage" + '404': + description: Item not found in the system + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the account to be checked + required: true + type: string + - name: from + in: query + description: Datetime from which to get the usage report + type: integer + - name: to + in: query + description: Datetime until which to get the usage report + type: integer + - name: resource + in: query + description: Resource type to filter the usage + type: string + - name: region + in: query + description: Resource region to filter the usage + type: string + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + ItemCreatedResponse: + properties: + ApiLink: + type: string + Message: + type: string + Metadata: + type: object + x-go-type: + import: + package: "gitlab.com/cyclops-enterprise/datamodels" + type: JSONdb + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + + Event: + type: object + required: + - EventTime + - LastEvent + properties: + Account: + type: string + x-go-custom-tag: gorm:"index" + EventTime: + type: integer + ID: + type: integer + x-go-custom-tag: gorm:"primary_key;auto_increment" + LastEvent: + type: string + enum: + - active + - error + - inactive + - terminated + - suspended + MetaData: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + Region: + type: string + ResourceId: + type: string + ResourceName: + type: string + ResourceType: + type: string + TimeFrom: + type: integer + x-go-custom-tag: gorm:"index" + TimeTo: + type: integer + x-go-custom-tag: gorm:"index" + + State: + type: object + required: + - EventTime + - LastEvent + properties: + Account: + type: string + x-go-custom-tag: gorm:"index" + EventTime: + type: integer + ID: + type: integer + x-go-custom-tag: gorm:"primary_key;auto_increment" + LastEvent: + type: string + enum: + - active + - error + - inactive + - terminated + - suspended + MetaData: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + Region: + type: string + ResourceId: + type: string + ResourceName: + type: string + ResourceType: + type: string + TimeFrom: + type: integer + x-go-custom-tag: gorm:"index" + TimeTo: + type: integer + x-go-custom-tag: gorm:"index" + + MinimalState: + type: object + properties: + Account: + type: string + MetaData: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + ResourceId: + type: string + ResourceName: + type: string + + Usage: + type: object + properties: + AccountId: + type: string + TimeFrom: + type: integer + TimeTo: + type: integer + Usage: + type: array + items: + $ref: '#/definitions/Use' + + Use: + type: object + properties: + MetaData: + $ref: '#/definitions/Metadata' + Region: + type: string + ResourceId: + type: string + ResourceName: + type: string + ResourceType: + type: string + Unit: + type: string + UsageBreakup: + $ref: '#/definitions/Metadata' diff --git a/services/plan-manager/README.md b/services/plan-manager/README.md new file mode 100644 index 0000000..6410463 --- /dev/null +++ b/services/plan-manager/README.md @@ -0,0 +1,26 @@ +# PLAN MANAGER SERVICE + +Cyclops Engine's Plan Manager Service implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + diff --git a/services/plan-manager/client/bundle_management/bundle_management_client.go b/services/plan-manager/client/bundle_management/bundle_management_client.go new file mode 100644 index 0000000..d89ac1a --- /dev/null +++ b/services/plan-manager/client/bundle_management/bundle_management_client.go @@ -0,0 +1,198 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the bundle management client +type API interface { + /* + CreateSkuBundle creates s k u bundle + + Creates a new sku bundle*/ + CreateSkuBundle(ctx context.Context, params *CreateSkuBundleParams) (*CreateSkuBundleCreated, error) + /* + GetSkuBundle gets specific sku bundle + + get sku bundle with given id*/ + GetSkuBundle(ctx context.Context, params *GetSkuBundleParams) (*GetSkuBundleOK, error) + /* + GetSkuBundleByName gets specific sku bundle + + get sku bundle with given name*/ + GetSkuBundleByName(ctx context.Context, params *GetSkuBundleByNameParams) (*GetSkuBundleByNameOK, error) + /* + ListSkuBundles lists s k u bundles + + lists all sku bundles*/ + ListSkuBundles(ctx context.Context, params *ListSkuBundlesParams) (*ListSkuBundlesOK, error) + /* + UpdateSkuBundle updates specific sku bundle + + Update sku bundle with given id*/ + UpdateSkuBundle(ctx context.Context, params *UpdateSkuBundleParams) (*UpdateSkuBundleOK, error) +} + +// New creates a new bundle management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for bundle management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +CreateSkuBundle creates s k u bundle + +Creates a new sku bundle +*/ +func (a *Client) CreateSkuBundle(ctx context.Context, params *CreateSkuBundleParams) (*CreateSkuBundleCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "createSkuBundle", + Method: "POST", + PathPattern: "/sku/bundle", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &CreateSkuBundleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*CreateSkuBundleCreated), nil + +} + +/* +GetSkuBundle gets specific sku bundle + +get sku bundle with given id +*/ +func (a *Client) GetSkuBundle(ctx context.Context, params *GetSkuBundleParams) (*GetSkuBundleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSkuBundle", + Method: "GET", + PathPattern: "/sku/bundle/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSkuBundleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSkuBundleOK), nil + +} + +/* +GetSkuBundleByName gets specific sku bundle + +get sku bundle with given name +*/ +func (a *Client) GetSkuBundleByName(ctx context.Context, params *GetSkuBundleByNameParams) (*GetSkuBundleByNameOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSkuBundleByName", + Method: "GET", + PathPattern: "/sku/bundle/name/{name}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSkuBundleByNameReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSkuBundleByNameOK), nil + +} + +/* +ListSkuBundles lists s k u bundles + +lists all sku bundles +*/ +func (a *Client) ListSkuBundles(ctx context.Context, params *ListSkuBundlesParams) (*ListSkuBundlesOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listSkuBundles", + Method: "GET", + PathPattern: "/sku/bundle", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListSkuBundlesReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListSkuBundlesOK), nil + +} + +/* +UpdateSkuBundle updates specific sku bundle + +Update sku bundle with given id +*/ +func (a *Client) UpdateSkuBundle(ctx context.Context, params *UpdateSkuBundleParams) (*UpdateSkuBundleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updateSkuBundle", + Method: "PUT", + PathPattern: "/sku/bundle/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdateSkuBundleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UpdateSkuBundleOK), nil + +} diff --git a/services/plan-manager/client/bundle_management/create_sku_bundle_parameters.go b/services/plan-manager/client/bundle_management/create_sku_bundle_parameters.go new file mode 100644 index 0000000..386c539 --- /dev/null +++ b/services/plan-manager/client/bundle_management/create_sku_bundle_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateSkuBundleParams creates a new CreateSkuBundleParams object +// with the default values initialized. +func NewCreateSkuBundleParams() *CreateSkuBundleParams { + var () + return &CreateSkuBundleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewCreateSkuBundleParamsWithTimeout creates a new CreateSkuBundleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewCreateSkuBundleParamsWithTimeout(timeout time.Duration) *CreateSkuBundleParams { + var () + return &CreateSkuBundleParams{ + + timeout: timeout, + } +} + +// NewCreateSkuBundleParamsWithContext creates a new CreateSkuBundleParams object +// with the default values initialized, and the ability to set a context for a request +func NewCreateSkuBundleParamsWithContext(ctx context.Context) *CreateSkuBundleParams { + var () + return &CreateSkuBundleParams{ + + Context: ctx, + } +} + +// NewCreateSkuBundleParamsWithHTTPClient creates a new CreateSkuBundleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewCreateSkuBundleParamsWithHTTPClient(client *http.Client) *CreateSkuBundleParams { + var () + return &CreateSkuBundleParams{ + HTTPClient: client, + } +} + +/*CreateSkuBundleParams contains all the parameters to send to the API endpoint +for the create sku bundle operation typically these are written to a http.Request +*/ +type CreateSkuBundleParams struct { + + /*Bundle + SKU bundle to be added + + */ + Bundle *models.SkuBundle + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the create sku bundle params +func (o *CreateSkuBundleParams) WithTimeout(timeout time.Duration) *CreateSkuBundleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create sku bundle params +func (o *CreateSkuBundleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create sku bundle params +func (o *CreateSkuBundleParams) WithContext(ctx context.Context) *CreateSkuBundleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create sku bundle params +func (o *CreateSkuBundleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create sku bundle params +func (o *CreateSkuBundleParams) WithHTTPClient(client *http.Client) *CreateSkuBundleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create sku bundle params +func (o *CreateSkuBundleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBundle adds the bundle to the create sku bundle params +func (o *CreateSkuBundleParams) WithBundle(bundle *models.SkuBundle) *CreateSkuBundleParams { + o.SetBundle(bundle) + return o +} + +// SetBundle adds the bundle to the create sku bundle params +func (o *CreateSkuBundleParams) SetBundle(bundle *models.SkuBundle) { + o.Bundle = bundle +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateSkuBundleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Bundle != nil { + if err := r.SetBodyParam(o.Bundle); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/bundle_management/create_sku_bundle_responses.go b/services/plan-manager/client/bundle_management/create_sku_bundle_responses.go new file mode 100644 index 0000000..43f43ce --- /dev/null +++ b/services/plan-manager/client/bundle_management/create_sku_bundle_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateSkuBundleReader is a Reader for the CreateSkuBundle structure. +type CreateSkuBundleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateSkuBundleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewCreateSkuBundleCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewCreateSkuBundleBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewCreateSkuBundleConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewCreateSkuBundleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewCreateSkuBundleCreated creates a CreateSkuBundleCreated with default headers values +func NewCreateSkuBundleCreated() *CreateSkuBundleCreated { + return &CreateSkuBundleCreated{} +} + +/*CreateSkuBundleCreated handles this case with default header values. + +item created +*/ +type CreateSkuBundleCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *CreateSkuBundleCreated) Error() string { + return fmt.Sprintf("[POST /sku/bundle][%d] createSkuBundleCreated %+v", 201, o.Payload) +} + +func (o *CreateSkuBundleCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *CreateSkuBundleCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateSkuBundleBadRequest creates a CreateSkuBundleBadRequest with default headers values +func NewCreateSkuBundleBadRequest() *CreateSkuBundleBadRequest { + return &CreateSkuBundleBadRequest{} +} + +/*CreateSkuBundleBadRequest handles this case with default header values. + +invalid input, object invalid +*/ +type CreateSkuBundleBadRequest struct { +} + +func (o *CreateSkuBundleBadRequest) Error() string { + return fmt.Sprintf("[POST /sku/bundle][%d] createSkuBundleBadRequest ", 400) +} + +func (o *CreateSkuBundleBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewCreateSkuBundleConflict creates a CreateSkuBundleConflict with default headers values +func NewCreateSkuBundleConflict() *CreateSkuBundleConflict { + return &CreateSkuBundleConflict{} +} + +/*CreateSkuBundleConflict handles this case with default header values. + +an existing item already exists +*/ +type CreateSkuBundleConflict struct { + Payload *models.ErrorResponse +} + +func (o *CreateSkuBundleConflict) Error() string { + return fmt.Sprintf("[POST /sku/bundle][%d] createSkuBundleConflict %+v", 409, o.Payload) +} + +func (o *CreateSkuBundleConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateSkuBundleConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateSkuBundleInternalServerError creates a CreateSkuBundleInternalServerError with default headers values +func NewCreateSkuBundleInternalServerError() *CreateSkuBundleInternalServerError { + return &CreateSkuBundleInternalServerError{} +} + +/*CreateSkuBundleInternalServerError handles this case with default header values. + +unexpected error +*/ +type CreateSkuBundleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *CreateSkuBundleInternalServerError) Error() string { + return fmt.Sprintf("[POST /sku/bundle][%d] createSkuBundleInternalServerError %+v", 500, o.Payload) +} + +func (o *CreateSkuBundleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateSkuBundleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/bundle_management/get_sku_bundle_by_name_parameters.go b/services/plan-manager/client/bundle_management/get_sku_bundle_by_name_parameters.go new file mode 100644 index 0000000..a18d1f8 --- /dev/null +++ b/services/plan-manager/client/bundle_management/get_sku_bundle_by_name_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuBundleByNameParams creates a new GetSkuBundleByNameParams object +// with the default values initialized. +func NewGetSkuBundleByNameParams() *GetSkuBundleByNameParams { + var () + return &GetSkuBundleByNameParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSkuBundleByNameParamsWithTimeout creates a new GetSkuBundleByNameParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSkuBundleByNameParamsWithTimeout(timeout time.Duration) *GetSkuBundleByNameParams { + var () + return &GetSkuBundleByNameParams{ + + timeout: timeout, + } +} + +// NewGetSkuBundleByNameParamsWithContext creates a new GetSkuBundleByNameParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSkuBundleByNameParamsWithContext(ctx context.Context) *GetSkuBundleByNameParams { + var () + return &GetSkuBundleByNameParams{ + + Context: ctx, + } +} + +// NewGetSkuBundleByNameParamsWithHTTPClient creates a new GetSkuBundleByNameParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSkuBundleByNameParamsWithHTTPClient(client *http.Client) *GetSkuBundleByNameParams { + var () + return &GetSkuBundleByNameParams{ + HTTPClient: client, + } +} + +/*GetSkuBundleByNameParams contains all the parameters to send to the API endpoint +for the get sku bundle by name operation typically these are written to a http.Request +*/ +type GetSkuBundleByNameParams struct { + + /*Name + Id of sku bundle to be obtained + + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) WithTimeout(timeout time.Duration) *GetSkuBundleByNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) WithContext(ctx context.Context) *GetSkuBundleByNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) WithHTTPClient(client *http.Client) *GetSkuBundleByNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithName adds the name to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) WithName(name string) *GetSkuBundleByNameParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get sku bundle by name params +func (o *GetSkuBundleByNameParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSkuBundleByNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/bundle_management/get_sku_bundle_by_name_responses.go b/services/plan-manager/client/bundle_management/get_sku_bundle_by_name_responses.go new file mode 100644 index 0000000..d19c606 --- /dev/null +++ b/services/plan-manager/client/bundle_management/get_sku_bundle_by_name_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuBundleByNameReader is a Reader for the GetSkuBundleByName structure. +type GetSkuBundleByNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSkuBundleByNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSkuBundleByNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetSkuBundleByNameNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetSkuBundleByNameInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetSkuBundleByNameOK creates a GetSkuBundleByNameOK with default headers values +func NewGetSkuBundleByNameOK() *GetSkuBundleByNameOK { + return &GetSkuBundleByNameOK{} +} + +/*GetSkuBundleByNameOK handles this case with default header values. + +sku bundle returned +*/ +type GetSkuBundleByNameOK struct { + Payload *models.SkuBundle +} + +func (o *GetSkuBundleByNameOK) Error() string { + return fmt.Sprintf("[GET /sku/bundle/name/{name}][%d] getSkuBundleByNameOK %+v", 200, o.Payload) +} + +func (o *GetSkuBundleByNameOK) GetPayload() *models.SkuBundle { + return o.Payload +} + +func (o *GetSkuBundleByNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SkuBundle) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuBundleByNameNotFound creates a GetSkuBundleByNameNotFound with default headers values +func NewGetSkuBundleByNameNotFound() *GetSkuBundleByNameNotFound { + return &GetSkuBundleByNameNotFound{} +} + +/*GetSkuBundleByNameNotFound handles this case with default header values. + +sku bundle with name not found +*/ +type GetSkuBundleByNameNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuBundleByNameNotFound) Error() string { + return fmt.Sprintf("[GET /sku/bundle/name/{name}][%d] getSkuBundleByNameNotFound %+v", 404, o.Payload) +} + +func (o *GetSkuBundleByNameNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuBundleByNameNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuBundleByNameInternalServerError creates a GetSkuBundleByNameInternalServerError with default headers values +func NewGetSkuBundleByNameInternalServerError() *GetSkuBundleByNameInternalServerError { + return &GetSkuBundleByNameInternalServerError{} +} + +/*GetSkuBundleByNameInternalServerError handles this case with default header values. + +unexpected error +*/ +type GetSkuBundleByNameInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuBundleByNameInternalServerError) Error() string { + return fmt.Sprintf("[GET /sku/bundle/name/{name}][%d] getSkuBundleByNameInternalServerError %+v", 500, o.Payload) +} + +func (o *GetSkuBundleByNameInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuBundleByNameInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/bundle_management/get_sku_bundle_parameters.go b/services/plan-manager/client/bundle_management/get_sku_bundle_parameters.go new file mode 100644 index 0000000..883f296 --- /dev/null +++ b/services/plan-manager/client/bundle_management/get_sku_bundle_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuBundleParams creates a new GetSkuBundleParams object +// with the default values initialized. +func NewGetSkuBundleParams() *GetSkuBundleParams { + var () + return &GetSkuBundleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSkuBundleParamsWithTimeout creates a new GetSkuBundleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSkuBundleParamsWithTimeout(timeout time.Duration) *GetSkuBundleParams { + var () + return &GetSkuBundleParams{ + + timeout: timeout, + } +} + +// NewGetSkuBundleParamsWithContext creates a new GetSkuBundleParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSkuBundleParamsWithContext(ctx context.Context) *GetSkuBundleParams { + var () + return &GetSkuBundleParams{ + + Context: ctx, + } +} + +// NewGetSkuBundleParamsWithHTTPClient creates a new GetSkuBundleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSkuBundleParamsWithHTTPClient(client *http.Client) *GetSkuBundleParams { + var () + return &GetSkuBundleParams{ + HTTPClient: client, + } +} + +/*GetSkuBundleParams contains all the parameters to send to the API endpoint +for the get sku bundle operation typically these are written to a http.Request +*/ +type GetSkuBundleParams struct { + + /*ID + Id of sku bundle to be obtained + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get sku bundle params +func (o *GetSkuBundleParams) WithTimeout(timeout time.Duration) *GetSkuBundleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get sku bundle params +func (o *GetSkuBundleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get sku bundle params +func (o *GetSkuBundleParams) WithContext(ctx context.Context) *GetSkuBundleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get sku bundle params +func (o *GetSkuBundleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get sku bundle params +func (o *GetSkuBundleParams) WithHTTPClient(client *http.Client) *GetSkuBundleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get sku bundle params +func (o *GetSkuBundleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get sku bundle params +func (o *GetSkuBundleParams) WithID(id string) *GetSkuBundleParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get sku bundle params +func (o *GetSkuBundleParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSkuBundleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/bundle_management/get_sku_bundle_responses.go b/services/plan-manager/client/bundle_management/get_sku_bundle_responses.go new file mode 100644 index 0000000..419af48 --- /dev/null +++ b/services/plan-manager/client/bundle_management/get_sku_bundle_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuBundleReader is a Reader for the GetSkuBundle structure. +type GetSkuBundleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSkuBundleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSkuBundleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetSkuBundleNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetSkuBundleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetSkuBundleOK creates a GetSkuBundleOK with default headers values +func NewGetSkuBundleOK() *GetSkuBundleOK { + return &GetSkuBundleOK{} +} + +/*GetSkuBundleOK handles this case with default header values. + +sku bundle returned +*/ +type GetSkuBundleOK struct { + Payload *models.SkuBundle +} + +func (o *GetSkuBundleOK) Error() string { + return fmt.Sprintf("[GET /sku/bundle/{id}][%d] getSkuBundleOK %+v", 200, o.Payload) +} + +func (o *GetSkuBundleOK) GetPayload() *models.SkuBundle { + return o.Payload +} + +func (o *GetSkuBundleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SkuBundle) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuBundleNotFound creates a GetSkuBundleNotFound with default headers values +func NewGetSkuBundleNotFound() *GetSkuBundleNotFound { + return &GetSkuBundleNotFound{} +} + +/*GetSkuBundleNotFound handles this case with default header values. + +sku bundle with id not found +*/ +type GetSkuBundleNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuBundleNotFound) Error() string { + return fmt.Sprintf("[GET /sku/bundle/{id}][%d] getSkuBundleNotFound %+v", 404, o.Payload) +} + +func (o *GetSkuBundleNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuBundleNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuBundleInternalServerError creates a GetSkuBundleInternalServerError with default headers values +func NewGetSkuBundleInternalServerError() *GetSkuBundleInternalServerError { + return &GetSkuBundleInternalServerError{} +} + +/*GetSkuBundleInternalServerError handles this case with default header values. + +unexpected error +*/ +type GetSkuBundleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuBundleInternalServerError) Error() string { + return fmt.Sprintf("[GET /sku/bundle/{id}][%d] getSkuBundleInternalServerError %+v", 500, o.Payload) +} + +func (o *GetSkuBundleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuBundleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/bundle_management/list_sku_bundles_parameters.go b/services/plan-manager/client/bundle_management/list_sku_bundles_parameters.go new file mode 100644 index 0000000..1373b83 --- /dev/null +++ b/services/plan-manager/client/bundle_management/list_sku_bundles_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListSkuBundlesParams creates a new ListSkuBundlesParams object +// with the default values initialized. +func NewListSkuBundlesParams() *ListSkuBundlesParams { + + return &ListSkuBundlesParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListSkuBundlesParamsWithTimeout creates a new ListSkuBundlesParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListSkuBundlesParamsWithTimeout(timeout time.Duration) *ListSkuBundlesParams { + + return &ListSkuBundlesParams{ + + timeout: timeout, + } +} + +// NewListSkuBundlesParamsWithContext creates a new ListSkuBundlesParams object +// with the default values initialized, and the ability to set a context for a request +func NewListSkuBundlesParamsWithContext(ctx context.Context) *ListSkuBundlesParams { + + return &ListSkuBundlesParams{ + + Context: ctx, + } +} + +// NewListSkuBundlesParamsWithHTTPClient creates a new ListSkuBundlesParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListSkuBundlesParamsWithHTTPClient(client *http.Client) *ListSkuBundlesParams { + + return &ListSkuBundlesParams{ + HTTPClient: client, + } +} + +/*ListSkuBundlesParams contains all the parameters to send to the API endpoint +for the list sku bundles operation typically these are written to a http.Request +*/ +type ListSkuBundlesParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list sku bundles params +func (o *ListSkuBundlesParams) WithTimeout(timeout time.Duration) *ListSkuBundlesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list sku bundles params +func (o *ListSkuBundlesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list sku bundles params +func (o *ListSkuBundlesParams) WithContext(ctx context.Context) *ListSkuBundlesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list sku bundles params +func (o *ListSkuBundlesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list sku bundles params +func (o *ListSkuBundlesParams) WithHTTPClient(client *http.Client) *ListSkuBundlesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list sku bundles params +func (o *ListSkuBundlesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListSkuBundlesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/bundle_management/list_sku_bundles_responses.go b/services/plan-manager/client/bundle_management/list_sku_bundles_responses.go new file mode 100644 index 0000000..bb0cdfd --- /dev/null +++ b/services/plan-manager/client/bundle_management/list_sku_bundles_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListSkuBundlesReader is a Reader for the ListSkuBundles structure. +type ListSkuBundlesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListSkuBundlesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListSkuBundlesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListSkuBundlesInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListSkuBundlesOK creates a ListSkuBundlesOK with default headers values +func NewListSkuBundlesOK() *ListSkuBundlesOK { + return &ListSkuBundlesOK{} +} + +/*ListSkuBundlesOK handles this case with default header values. + +list of skus bundles returned +*/ +type ListSkuBundlesOK struct { + Payload []*models.SkuBundle +} + +func (o *ListSkuBundlesOK) Error() string { + return fmt.Sprintf("[GET /sku/bundle][%d] listSkuBundlesOK %+v", 200, o.Payload) +} + +func (o *ListSkuBundlesOK) GetPayload() []*models.SkuBundle { + return o.Payload +} + +func (o *ListSkuBundlesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListSkuBundlesInternalServerError creates a ListSkuBundlesInternalServerError with default headers values +func NewListSkuBundlesInternalServerError() *ListSkuBundlesInternalServerError { + return &ListSkuBundlesInternalServerError{} +} + +/*ListSkuBundlesInternalServerError handles this case with default header values. + +unexpected error +*/ +type ListSkuBundlesInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListSkuBundlesInternalServerError) Error() string { + return fmt.Sprintf("[GET /sku/bundle][%d] listSkuBundlesInternalServerError %+v", 500, o.Payload) +} + +func (o *ListSkuBundlesInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListSkuBundlesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/bundle_management/update_sku_bundle_parameters.go b/services/plan-manager/client/bundle_management/update_sku_bundle_parameters.go new file mode 100644 index 0000000..d967ab0 --- /dev/null +++ b/services/plan-manager/client/bundle_management/update_sku_bundle_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateSkuBundleParams creates a new UpdateSkuBundleParams object +// with the default values initialized. +func NewUpdateSkuBundleParams() *UpdateSkuBundleParams { + var () + return &UpdateSkuBundleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateSkuBundleParamsWithTimeout creates a new UpdateSkuBundleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdateSkuBundleParamsWithTimeout(timeout time.Duration) *UpdateSkuBundleParams { + var () + return &UpdateSkuBundleParams{ + + timeout: timeout, + } +} + +// NewUpdateSkuBundleParamsWithContext creates a new UpdateSkuBundleParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdateSkuBundleParamsWithContext(ctx context.Context) *UpdateSkuBundleParams { + var () + return &UpdateSkuBundleParams{ + + Context: ctx, + } +} + +// NewUpdateSkuBundleParamsWithHTTPClient creates a new UpdateSkuBundleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdateSkuBundleParamsWithHTTPClient(client *http.Client) *UpdateSkuBundleParams { + var () + return &UpdateSkuBundleParams{ + HTTPClient: client, + } +} + +/*UpdateSkuBundleParams contains all the parameters to send to the API endpoint +for the update sku bundle operation typically these are written to a http.Request +*/ +type UpdateSkuBundleParams struct { + + /*Bundle + updated sku bundle containing all parameters except id + + */ + Bundle *models.SkuBundle + /*ID + Id of sku bundle to be obtained + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update sku bundle params +func (o *UpdateSkuBundleParams) WithTimeout(timeout time.Duration) *UpdateSkuBundleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update sku bundle params +func (o *UpdateSkuBundleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update sku bundle params +func (o *UpdateSkuBundleParams) WithContext(ctx context.Context) *UpdateSkuBundleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update sku bundle params +func (o *UpdateSkuBundleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update sku bundle params +func (o *UpdateSkuBundleParams) WithHTTPClient(client *http.Client) *UpdateSkuBundleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update sku bundle params +func (o *UpdateSkuBundleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithBundle adds the bundle to the update sku bundle params +func (o *UpdateSkuBundleParams) WithBundle(bundle *models.SkuBundle) *UpdateSkuBundleParams { + o.SetBundle(bundle) + return o +} + +// SetBundle adds the bundle to the update sku bundle params +func (o *UpdateSkuBundleParams) SetBundle(bundle *models.SkuBundle) { + o.Bundle = bundle +} + +// WithID adds the id to the update sku bundle params +func (o *UpdateSkuBundleParams) WithID(id string) *UpdateSkuBundleParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update sku bundle params +func (o *UpdateSkuBundleParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateSkuBundleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Bundle != nil { + if err := r.SetBodyParam(o.Bundle); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/bundle_management/update_sku_bundle_responses.go b/services/plan-manager/client/bundle_management/update_sku_bundle_responses.go new file mode 100644 index 0000000..1066ea4 --- /dev/null +++ b/services/plan-manager/client/bundle_management/update_sku_bundle_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateSkuBundleReader is a Reader for the UpdateSkuBundle structure. +type UpdateSkuBundleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateSkuBundleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateSkuBundleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdateSkuBundleNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdateSkuBundleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewUpdateSkuBundleOK creates a UpdateSkuBundleOK with default headers values +func NewUpdateSkuBundleOK() *UpdateSkuBundleOK { + return &UpdateSkuBundleOK{} +} + +/*UpdateSkuBundleOK handles this case with default header values. + +updated sku bundle +*/ +type UpdateSkuBundleOK struct { + Payload *models.SkuBundle +} + +func (o *UpdateSkuBundleOK) Error() string { + return fmt.Sprintf("[PUT /sku/bundle/{id}][%d] updateSkuBundleOK %+v", 200, o.Payload) +} + +func (o *UpdateSkuBundleOK) GetPayload() *models.SkuBundle { + return o.Payload +} + +func (o *UpdateSkuBundleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SkuBundle) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateSkuBundleNotFound creates a UpdateSkuBundleNotFound with default headers values +func NewUpdateSkuBundleNotFound() *UpdateSkuBundleNotFound { + return &UpdateSkuBundleNotFound{} +} + +/*UpdateSkuBundleNotFound handles this case with default header values. + +sku bundle with id not found +*/ +type UpdateSkuBundleNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdateSkuBundleNotFound) Error() string { + return fmt.Sprintf("[PUT /sku/bundle/{id}][%d] updateSkuBundleNotFound %+v", 404, o.Payload) +} + +func (o *UpdateSkuBundleNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateSkuBundleNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateSkuBundleInternalServerError creates a UpdateSkuBundleInternalServerError with default headers values +func NewUpdateSkuBundleInternalServerError() *UpdateSkuBundleInternalServerError { + return &UpdateSkuBundleInternalServerError{} +} + +/*UpdateSkuBundleInternalServerError handles this case with default header values. + +unexpected error +*/ +type UpdateSkuBundleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdateSkuBundleInternalServerError) Error() string { + return fmt.Sprintf("[PUT /sku/bundle/{id}][%d] updateSkuBundleInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdateSkuBundleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateSkuBundleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/cycle_management/create_cycle_parameters.go b/services/plan-manager/client/cycle_management/create_cycle_parameters.go new file mode 100644 index 0000000..894bab1 --- /dev/null +++ b/services/plan-manager/client/cycle_management/create_cycle_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateCycleParams creates a new CreateCycleParams object +// with the default values initialized. +func NewCreateCycleParams() *CreateCycleParams { + var () + return &CreateCycleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewCreateCycleParamsWithTimeout creates a new CreateCycleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewCreateCycleParamsWithTimeout(timeout time.Duration) *CreateCycleParams { + var () + return &CreateCycleParams{ + + timeout: timeout, + } +} + +// NewCreateCycleParamsWithContext creates a new CreateCycleParams object +// with the default values initialized, and the ability to set a context for a request +func NewCreateCycleParamsWithContext(ctx context.Context) *CreateCycleParams { + var () + return &CreateCycleParams{ + + Context: ctx, + } +} + +// NewCreateCycleParamsWithHTTPClient creates a new CreateCycleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewCreateCycleParamsWithHTTPClient(client *http.Client) *CreateCycleParams { + var () + return &CreateCycleParams{ + HTTPClient: client, + } +} + +/*CreateCycleParams contains all the parameters to send to the API endpoint +for the create cycle operation typically these are written to a http.Request +*/ +type CreateCycleParams struct { + + /*Cycle + Cycle to be added + + */ + Cycle *models.Cycle + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the create cycle params +func (o *CreateCycleParams) WithTimeout(timeout time.Duration) *CreateCycleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create cycle params +func (o *CreateCycleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create cycle params +func (o *CreateCycleParams) WithContext(ctx context.Context) *CreateCycleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create cycle params +func (o *CreateCycleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create cycle params +func (o *CreateCycleParams) WithHTTPClient(client *http.Client) *CreateCycleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create cycle params +func (o *CreateCycleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCycle adds the cycle to the create cycle params +func (o *CreateCycleParams) WithCycle(cycle *models.Cycle) *CreateCycleParams { + o.SetCycle(cycle) + return o +} + +// SetCycle adds the cycle to the create cycle params +func (o *CreateCycleParams) SetCycle(cycle *models.Cycle) { + o.Cycle = cycle +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateCycleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Cycle != nil { + if err := r.SetBodyParam(o.Cycle); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/cycle_management/create_cycle_responses.go b/services/plan-manager/client/cycle_management/create_cycle_responses.go new file mode 100644 index 0000000..15f41b8 --- /dev/null +++ b/services/plan-manager/client/cycle_management/create_cycle_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateCycleReader is a Reader for the CreateCycle structure. +type CreateCycleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateCycleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewCreateCycleCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewCreateCycleBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewCreateCycleConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewCreateCycleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewCreateCycleCreated creates a CreateCycleCreated with default headers values +func NewCreateCycleCreated() *CreateCycleCreated { + return &CreateCycleCreated{} +} + +/*CreateCycleCreated handles this case with default header values. + +item created +*/ +type CreateCycleCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *CreateCycleCreated) Error() string { + return fmt.Sprintf("[POST /cycle][%d] createCycleCreated %+v", 201, o.Payload) +} + +func (o *CreateCycleCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *CreateCycleCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateCycleBadRequest creates a CreateCycleBadRequest with default headers values +func NewCreateCycleBadRequest() *CreateCycleBadRequest { + return &CreateCycleBadRequest{} +} + +/*CreateCycleBadRequest handles this case with default header values. + +invalid input, object invalid +*/ +type CreateCycleBadRequest struct { +} + +func (o *CreateCycleBadRequest) Error() string { + return fmt.Sprintf("[POST /cycle][%d] createCycleBadRequest ", 400) +} + +func (o *CreateCycleBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewCreateCycleConflict creates a CreateCycleConflict with default headers values +func NewCreateCycleConflict() *CreateCycleConflict { + return &CreateCycleConflict{} +} + +/*CreateCycleConflict handles this case with default header values. + +an existing item already exists +*/ +type CreateCycleConflict struct { + Payload *models.ErrorResponse +} + +func (o *CreateCycleConflict) Error() string { + return fmt.Sprintf("[POST /cycle][%d] createCycleConflict %+v", 409, o.Payload) +} + +func (o *CreateCycleConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateCycleConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateCycleInternalServerError creates a CreateCycleInternalServerError with default headers values +func NewCreateCycleInternalServerError() *CreateCycleInternalServerError { + return &CreateCycleInternalServerError{} +} + +/*CreateCycleInternalServerError handles this case with default header values. + +unexpected error +*/ +type CreateCycleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *CreateCycleInternalServerError) Error() string { + return fmt.Sprintf("[POST /cycle][%d] createCycleInternalServerError %+v", 500, o.Payload) +} + +func (o *CreateCycleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateCycleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/cycle_management/cycle_management_client.go b/services/plan-manager/client/cycle_management/cycle_management_client.go new file mode 100644 index 0000000..24f3e22 --- /dev/null +++ b/services/plan-manager/client/cycle_management/cycle_management_client.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the cycle management client +type API interface { + /* + CreateCycle creates a plan + + Creates a new cycle*/ + CreateCycle(ctx context.Context, params *CreateCycleParams) (*CreateCycleCreated, error) + /* + GetCycle gets specific cycle + + get cycle with given id*/ + GetCycle(ctx context.Context, params *GetCycleParams) (*GetCycleOK, error) + /* + ListCycles lists all cycles + + lists all cycles*/ + ListCycles(ctx context.Context, params *ListCyclesParams) (*ListCyclesOK, error) + /* + UpdateCycle updates specific cycle + + Update cycle with given id*/ + UpdateCycle(ctx context.Context, params *UpdateCycleParams) (*UpdateCycleOK, error) +} + +// New creates a new cycle management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for cycle management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +CreateCycle creates a plan + +Creates a new cycle +*/ +func (a *Client) CreateCycle(ctx context.Context, params *CreateCycleParams) (*CreateCycleCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "createCycle", + Method: "POST", + PathPattern: "/cycle", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &CreateCycleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*CreateCycleCreated), nil + +} + +/* +GetCycle gets specific cycle + +get cycle with given id +*/ +func (a *Client) GetCycle(ctx context.Context, params *GetCycleParams) (*GetCycleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getCycle", + Method: "GET", + PathPattern: "/cycle/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetCycleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetCycleOK), nil + +} + +/* +ListCycles lists all cycles + +lists all cycles +*/ +func (a *Client) ListCycles(ctx context.Context, params *ListCyclesParams) (*ListCyclesOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listCycles", + Method: "GET", + PathPattern: "/cycle", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListCyclesReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListCyclesOK), nil + +} + +/* +UpdateCycle updates specific cycle + +Update cycle with given id +*/ +func (a *Client) UpdateCycle(ctx context.Context, params *UpdateCycleParams) (*UpdateCycleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updateCycle", + Method: "PUT", + PathPattern: "/cycle/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdateCycleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UpdateCycleOK), nil + +} diff --git a/services/plan-manager/client/cycle_management/get_cycle_parameters.go b/services/plan-manager/client/cycle_management/get_cycle_parameters.go new file mode 100644 index 0000000..0907d83 --- /dev/null +++ b/services/plan-manager/client/cycle_management/get_cycle_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCycleParams creates a new GetCycleParams object +// with the default values initialized. +func NewGetCycleParams() *GetCycleParams { + var () + return &GetCycleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetCycleParamsWithTimeout creates a new GetCycleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetCycleParamsWithTimeout(timeout time.Duration) *GetCycleParams { + var () + return &GetCycleParams{ + + timeout: timeout, + } +} + +// NewGetCycleParamsWithContext creates a new GetCycleParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetCycleParamsWithContext(ctx context.Context) *GetCycleParams { + var () + return &GetCycleParams{ + + Context: ctx, + } +} + +// NewGetCycleParamsWithHTTPClient creates a new GetCycleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetCycleParamsWithHTTPClient(client *http.Client) *GetCycleParams { + var () + return &GetCycleParams{ + HTTPClient: client, + } +} + +/*GetCycleParams contains all the parameters to send to the API endpoint +for the get cycle operation typically these are written to a http.Request +*/ +type GetCycleParams struct { + + /*ID + Id of cycle to be obtained + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get cycle params +func (o *GetCycleParams) WithTimeout(timeout time.Duration) *GetCycleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get cycle params +func (o *GetCycleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get cycle params +func (o *GetCycleParams) WithContext(ctx context.Context) *GetCycleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get cycle params +func (o *GetCycleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get cycle params +func (o *GetCycleParams) WithHTTPClient(client *http.Client) *GetCycleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get cycle params +func (o *GetCycleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get cycle params +func (o *GetCycleParams) WithID(id string) *GetCycleParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get cycle params +func (o *GetCycleParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCycleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/cycle_management/get_cycle_responses.go b/services/plan-manager/client/cycle_management/get_cycle_responses.go new file mode 100644 index 0000000..a8c6335 --- /dev/null +++ b/services/plan-manager/client/cycle_management/get_cycle_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetCycleReader is a Reader for the GetCycle structure. +type GetCycleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCycleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCycleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetCycleNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetCycleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetCycleOK creates a GetCycleOK with default headers values +func NewGetCycleOK() *GetCycleOK { + return &GetCycleOK{} +} + +/*GetCycleOK handles this case with default header values. + +cycle returned +*/ +type GetCycleOK struct { + Payload *models.Cycle +} + +func (o *GetCycleOK) Error() string { + return fmt.Sprintf("[GET /cycle/{id}][%d] getCycleOK %+v", 200, o.Payload) +} + +func (o *GetCycleOK) GetPayload() *models.Cycle { + return o.Payload +} + +func (o *GetCycleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Cycle) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCycleNotFound creates a GetCycleNotFound with default headers values +func NewGetCycleNotFound() *GetCycleNotFound { + return &GetCycleNotFound{} +} + +/*GetCycleNotFound handles this case with default header values. + +cycle with id not found +*/ +type GetCycleNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetCycleNotFound) Error() string { + return fmt.Sprintf("[GET /cycle/{id}][%d] getCycleNotFound %+v", 404, o.Payload) +} + +func (o *GetCycleNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCycleNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCycleInternalServerError creates a GetCycleInternalServerError with default headers values +func NewGetCycleInternalServerError() *GetCycleInternalServerError { + return &GetCycleInternalServerError{} +} + +/*GetCycleInternalServerError handles this case with default header values. + +unexpected error +*/ +type GetCycleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetCycleInternalServerError) Error() string { + return fmt.Sprintf("[GET /cycle/{id}][%d] getCycleInternalServerError %+v", 500, o.Payload) +} + +func (o *GetCycleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCycleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/cycle_management/list_cycles_parameters.go b/services/plan-manager/client/cycle_management/list_cycles_parameters.go new file mode 100644 index 0000000..1d5775b --- /dev/null +++ b/services/plan-manager/client/cycle_management/list_cycles_parameters.go @@ -0,0 +1,178 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListCyclesParams creates a new ListCyclesParams object +// with the default values initialized. +func NewListCyclesParams() *ListCyclesParams { + var () + return &ListCyclesParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListCyclesParamsWithTimeout creates a new ListCyclesParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListCyclesParamsWithTimeout(timeout time.Duration) *ListCyclesParams { + var () + return &ListCyclesParams{ + + timeout: timeout, + } +} + +// NewListCyclesParamsWithContext creates a new ListCyclesParams object +// with the default values initialized, and the ability to set a context for a request +func NewListCyclesParamsWithContext(ctx context.Context) *ListCyclesParams { + var () + return &ListCyclesParams{ + + Context: ctx, + } +} + +// NewListCyclesParamsWithHTTPClient creates a new ListCyclesParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListCyclesParamsWithHTTPClient(client *http.Client) *ListCyclesParams { + var () + return &ListCyclesParams{ + HTTPClient: client, + } +} + +/*ListCyclesParams contains all the parameters to send to the API endpoint +for the list cycles operation typically these are written to a http.Request +*/ +type ListCyclesParams struct { + + /*State + state to filter + + */ + State *string + /*Type + resource type to filter + + */ + Type *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list cycles params +func (o *ListCyclesParams) WithTimeout(timeout time.Duration) *ListCyclesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list cycles params +func (o *ListCyclesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list cycles params +func (o *ListCyclesParams) WithContext(ctx context.Context) *ListCyclesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list cycles params +func (o *ListCyclesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list cycles params +func (o *ListCyclesParams) WithHTTPClient(client *http.Client) *ListCyclesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list cycles params +func (o *ListCyclesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithState adds the state to the list cycles params +func (o *ListCyclesParams) WithState(state *string) *ListCyclesParams { + o.SetState(state) + return o +} + +// SetState adds the state to the list cycles params +func (o *ListCyclesParams) SetState(state *string) { + o.State = state +} + +// WithType adds the typeVar to the list cycles params +func (o *ListCyclesParams) WithType(typeVar *string) *ListCyclesParams { + o.SetType(typeVar) + return o +} + +// SetType adds the type to the list cycles params +func (o *ListCyclesParams) SetType(typeVar *string) { + o.Type = typeVar +} + +// WriteToRequest writes these params to a swagger request +func (o *ListCyclesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.State != nil { + + // query param state + var qrState string + if o.State != nil { + qrState = *o.State + } + qState := qrState + if qState != "" { + if err := r.SetQueryParam("state", qState); err != nil { + return err + } + } + + } + + if o.Type != nil { + + // query param type + var qrType string + if o.Type != nil { + qrType = *o.Type + } + qType := qrType + if qType != "" { + if err := r.SetQueryParam("type", qType); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/cycle_management/list_cycles_responses.go b/services/plan-manager/client/cycle_management/list_cycles_responses.go new file mode 100644 index 0000000..fab34ca --- /dev/null +++ b/services/plan-manager/client/cycle_management/list_cycles_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListCyclesReader is a Reader for the ListCycles structure. +type ListCyclesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListCyclesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListCyclesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListCyclesInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListCyclesOK creates a ListCyclesOK with default headers values +func NewListCyclesOK() *ListCyclesOK { + return &ListCyclesOK{} +} + +/*ListCyclesOK handles this case with default header values. + +list of cycles returned +*/ +type ListCyclesOK struct { + Payload []*models.Cycle +} + +func (o *ListCyclesOK) Error() string { + return fmt.Sprintf("[GET /cycle][%d] listCyclesOK %+v", 200, o.Payload) +} + +func (o *ListCyclesOK) GetPayload() []*models.Cycle { + return o.Payload +} + +func (o *ListCyclesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListCyclesInternalServerError creates a ListCyclesInternalServerError with default headers values +func NewListCyclesInternalServerError() *ListCyclesInternalServerError { + return &ListCyclesInternalServerError{} +} + +/*ListCyclesInternalServerError handles this case with default header values. + +unexpected error +*/ +type ListCyclesInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListCyclesInternalServerError) Error() string { + return fmt.Sprintf("[GET /cycle][%d] listCyclesInternalServerError %+v", 500, o.Payload) +} + +func (o *ListCyclesInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListCyclesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/cycle_management/update_cycle_parameters.go b/services/plan-manager/client/cycle_management/update_cycle_parameters.go new file mode 100644 index 0000000..3001381 --- /dev/null +++ b/services/plan-manager/client/cycle_management/update_cycle_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateCycleParams creates a new UpdateCycleParams object +// with the default values initialized. +func NewUpdateCycleParams() *UpdateCycleParams { + var () + return &UpdateCycleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateCycleParamsWithTimeout creates a new UpdateCycleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdateCycleParamsWithTimeout(timeout time.Duration) *UpdateCycleParams { + var () + return &UpdateCycleParams{ + + timeout: timeout, + } +} + +// NewUpdateCycleParamsWithContext creates a new UpdateCycleParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdateCycleParamsWithContext(ctx context.Context) *UpdateCycleParams { + var () + return &UpdateCycleParams{ + + Context: ctx, + } +} + +// NewUpdateCycleParamsWithHTTPClient creates a new UpdateCycleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdateCycleParamsWithHTTPClient(client *http.Client) *UpdateCycleParams { + var () + return &UpdateCycleParams{ + HTTPClient: client, + } +} + +/*UpdateCycleParams contains all the parameters to send to the API endpoint +for the update cycle operation typically these are written to a http.Request +*/ +type UpdateCycleParams struct { + + /*Cycle + updated cycle containing all parameters except id + + */ + Cycle *models.Cycle + /*ID + Id of cycle to be updated + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update cycle params +func (o *UpdateCycleParams) WithTimeout(timeout time.Duration) *UpdateCycleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update cycle params +func (o *UpdateCycleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update cycle params +func (o *UpdateCycleParams) WithContext(ctx context.Context) *UpdateCycleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update cycle params +func (o *UpdateCycleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update cycle params +func (o *UpdateCycleParams) WithHTTPClient(client *http.Client) *UpdateCycleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update cycle params +func (o *UpdateCycleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCycle adds the cycle to the update cycle params +func (o *UpdateCycleParams) WithCycle(cycle *models.Cycle) *UpdateCycleParams { + o.SetCycle(cycle) + return o +} + +// SetCycle adds the cycle to the update cycle params +func (o *UpdateCycleParams) SetCycle(cycle *models.Cycle) { + o.Cycle = cycle +} + +// WithID adds the id to the update cycle params +func (o *UpdateCycleParams) WithID(id string) *UpdateCycleParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update cycle params +func (o *UpdateCycleParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateCycleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Cycle != nil { + if err := r.SetBodyParam(o.Cycle); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/cycle_management/update_cycle_responses.go b/services/plan-manager/client/cycle_management/update_cycle_responses.go new file mode 100644 index 0000000..b21f06c --- /dev/null +++ b/services/plan-manager/client/cycle_management/update_cycle_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateCycleReader is a Reader for the UpdateCycle structure. +type UpdateCycleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateCycleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateCycleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdateCycleNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdateCycleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewUpdateCycleOK creates a UpdateCycleOK with default headers values +func NewUpdateCycleOK() *UpdateCycleOK { + return &UpdateCycleOK{} +} + +/*UpdateCycleOK handles this case with default header values. + +updated cycle +*/ +type UpdateCycleOK struct { + Payload *models.Cycle +} + +func (o *UpdateCycleOK) Error() string { + return fmt.Sprintf("[PUT /cycle/{id}][%d] updateCycleOK %+v", 200, o.Payload) +} + +func (o *UpdateCycleOK) GetPayload() *models.Cycle { + return o.Payload +} + +func (o *UpdateCycleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Cycle) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateCycleNotFound creates a UpdateCycleNotFound with default headers values +func NewUpdateCycleNotFound() *UpdateCycleNotFound { + return &UpdateCycleNotFound{} +} + +/*UpdateCycleNotFound handles this case with default header values. + +cycle with id not found +*/ +type UpdateCycleNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdateCycleNotFound) Error() string { + return fmt.Sprintf("[PUT /cycle/{id}][%d] updateCycleNotFound %+v", 404, o.Payload) +} + +func (o *UpdateCycleNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateCycleNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateCycleInternalServerError creates a UpdateCycleInternalServerError with default headers values +func NewUpdateCycleInternalServerError() *UpdateCycleInternalServerError { + return &UpdateCycleInternalServerError{} +} + +/*UpdateCycleInternalServerError handles this case with default header values. + +unexpected error +*/ +type UpdateCycleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdateCycleInternalServerError) Error() string { + return fmt.Sprintf("[PUT /cycle/{id}][%d] updateCycleInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdateCycleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateCycleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/plan_management/create_plan_parameters.go b/services/plan-manager/client/plan_management/create_plan_parameters.go new file mode 100644 index 0000000..dc72001 --- /dev/null +++ b/services/plan-manager/client/plan_management/create_plan_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreatePlanParams creates a new CreatePlanParams object +// with the default values initialized. +func NewCreatePlanParams() *CreatePlanParams { + var () + return &CreatePlanParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewCreatePlanParamsWithTimeout creates a new CreatePlanParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewCreatePlanParamsWithTimeout(timeout time.Duration) *CreatePlanParams { + var () + return &CreatePlanParams{ + + timeout: timeout, + } +} + +// NewCreatePlanParamsWithContext creates a new CreatePlanParams object +// with the default values initialized, and the ability to set a context for a request +func NewCreatePlanParamsWithContext(ctx context.Context) *CreatePlanParams { + var () + return &CreatePlanParams{ + + Context: ctx, + } +} + +// NewCreatePlanParamsWithHTTPClient creates a new CreatePlanParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewCreatePlanParamsWithHTTPClient(client *http.Client) *CreatePlanParams { + var () + return &CreatePlanParams{ + HTTPClient: client, + } +} + +/*CreatePlanParams contains all the parameters to send to the API endpoint +for the create plan operation typically these are written to a http.Request +*/ +type CreatePlanParams struct { + + /*Plan + Plan to be added + + */ + Plan *models.Plan + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the create plan params +func (o *CreatePlanParams) WithTimeout(timeout time.Duration) *CreatePlanParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create plan params +func (o *CreatePlanParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create plan params +func (o *CreatePlanParams) WithContext(ctx context.Context) *CreatePlanParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create plan params +func (o *CreatePlanParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create plan params +func (o *CreatePlanParams) WithHTTPClient(client *http.Client) *CreatePlanParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create plan params +func (o *CreatePlanParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithPlan adds the plan to the create plan params +func (o *CreatePlanParams) WithPlan(plan *models.Plan) *CreatePlanParams { + o.SetPlan(plan) + return o +} + +// SetPlan adds the plan to the create plan params +func (o *CreatePlanParams) SetPlan(plan *models.Plan) { + o.Plan = plan +} + +// WriteToRequest writes these params to a swagger request +func (o *CreatePlanParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Plan != nil { + if err := r.SetBodyParam(o.Plan); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/plan_management/create_plan_responses.go b/services/plan-manager/client/plan_management/create_plan_responses.go new file mode 100644 index 0000000..e59b6e7 --- /dev/null +++ b/services/plan-manager/client/plan_management/create_plan_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreatePlanReader is a Reader for the CreatePlan structure. +type CreatePlanReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreatePlanReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewCreatePlanCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewCreatePlanBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewCreatePlanConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewCreatePlanInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewCreatePlanCreated creates a CreatePlanCreated with default headers values +func NewCreatePlanCreated() *CreatePlanCreated { + return &CreatePlanCreated{} +} + +/*CreatePlanCreated handles this case with default header values. + +item created +*/ +type CreatePlanCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *CreatePlanCreated) Error() string { + return fmt.Sprintf("[POST /plan][%d] createPlanCreated %+v", 201, o.Payload) +} + +func (o *CreatePlanCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *CreatePlanCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreatePlanBadRequest creates a CreatePlanBadRequest with default headers values +func NewCreatePlanBadRequest() *CreatePlanBadRequest { + return &CreatePlanBadRequest{} +} + +/*CreatePlanBadRequest handles this case with default header values. + +invalid input, object invalid +*/ +type CreatePlanBadRequest struct { +} + +func (o *CreatePlanBadRequest) Error() string { + return fmt.Sprintf("[POST /plan][%d] createPlanBadRequest ", 400) +} + +func (o *CreatePlanBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewCreatePlanConflict creates a CreatePlanConflict with default headers values +func NewCreatePlanConflict() *CreatePlanConflict { + return &CreatePlanConflict{} +} + +/*CreatePlanConflict handles this case with default header values. + +an existing item already exists +*/ +type CreatePlanConflict struct { + Payload *models.ErrorResponse +} + +func (o *CreatePlanConflict) Error() string { + return fmt.Sprintf("[POST /plan][%d] createPlanConflict %+v", 409, o.Payload) +} + +func (o *CreatePlanConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreatePlanConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreatePlanInternalServerError creates a CreatePlanInternalServerError with default headers values +func NewCreatePlanInternalServerError() *CreatePlanInternalServerError { + return &CreatePlanInternalServerError{} +} + +/*CreatePlanInternalServerError handles this case with default header values. + +unexpected error +*/ +type CreatePlanInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *CreatePlanInternalServerError) Error() string { + return fmt.Sprintf("[POST /plan][%d] createPlanInternalServerError %+v", 500, o.Payload) +} + +func (o *CreatePlanInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreatePlanInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/plan_management/get_complete_plan_parameters.go b/services/plan-manager/client/plan_management/get_complete_plan_parameters.go new file mode 100644 index 0000000..5cdfcaf --- /dev/null +++ b/services/plan-manager/client/plan_management/get_complete_plan_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCompletePlanParams creates a new GetCompletePlanParams object +// with the default values initialized. +func NewGetCompletePlanParams() *GetCompletePlanParams { + var () + return &GetCompletePlanParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetCompletePlanParamsWithTimeout creates a new GetCompletePlanParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetCompletePlanParamsWithTimeout(timeout time.Duration) *GetCompletePlanParams { + var () + return &GetCompletePlanParams{ + + timeout: timeout, + } +} + +// NewGetCompletePlanParamsWithContext creates a new GetCompletePlanParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetCompletePlanParamsWithContext(ctx context.Context) *GetCompletePlanParams { + var () + return &GetCompletePlanParams{ + + Context: ctx, + } +} + +// NewGetCompletePlanParamsWithHTTPClient creates a new GetCompletePlanParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetCompletePlanParamsWithHTTPClient(client *http.Client) *GetCompletePlanParams { + var () + return &GetCompletePlanParams{ + HTTPClient: client, + } +} + +/*GetCompletePlanParams contains all the parameters to send to the API endpoint +for the get complete plan operation typically these are written to a http.Request +*/ +type GetCompletePlanParams struct { + + /*ID + Id of plan to be obtained + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get complete plan params +func (o *GetCompletePlanParams) WithTimeout(timeout time.Duration) *GetCompletePlanParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get complete plan params +func (o *GetCompletePlanParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get complete plan params +func (o *GetCompletePlanParams) WithContext(ctx context.Context) *GetCompletePlanParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get complete plan params +func (o *GetCompletePlanParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get complete plan params +func (o *GetCompletePlanParams) WithHTTPClient(client *http.Client) *GetCompletePlanParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get complete plan params +func (o *GetCompletePlanParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get complete plan params +func (o *GetCompletePlanParams) WithID(id string) *GetCompletePlanParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get complete plan params +func (o *GetCompletePlanParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCompletePlanParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/plan_management/get_complete_plan_responses.go b/services/plan-manager/client/plan_management/get_complete_plan_responses.go new file mode 100644 index 0000000..c1b05d7 --- /dev/null +++ b/services/plan-manager/client/plan_management/get_complete_plan_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetCompletePlanReader is a Reader for the GetCompletePlan structure. +type GetCompletePlanReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCompletePlanReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCompletePlanOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetCompletePlanNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetCompletePlanInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetCompletePlanOK creates a GetCompletePlanOK with default headers values +func NewGetCompletePlanOK() *GetCompletePlanOK { + return &GetCompletePlanOK{} +} + +/*GetCompletePlanOK handles this case with default header values. + +plan returned +*/ +type GetCompletePlanOK struct { + Payload *models.Plan +} + +func (o *GetCompletePlanOK) Error() string { + return fmt.Sprintf("[GET /plan/complete/{id}][%d] getCompletePlanOK %+v", 200, o.Payload) +} + +func (o *GetCompletePlanOK) GetPayload() *models.Plan { + return o.Payload +} + +func (o *GetCompletePlanOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Plan) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCompletePlanNotFound creates a GetCompletePlanNotFound with default headers values +func NewGetCompletePlanNotFound() *GetCompletePlanNotFound { + return &GetCompletePlanNotFound{} +} + +/*GetCompletePlanNotFound handles this case with default header values. + +complete plan with planid not found +*/ +type GetCompletePlanNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetCompletePlanNotFound) Error() string { + return fmt.Sprintf("[GET /plan/complete/{id}][%d] getCompletePlanNotFound %+v", 404, o.Payload) +} + +func (o *GetCompletePlanNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCompletePlanNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCompletePlanInternalServerError creates a GetCompletePlanInternalServerError with default headers values +func NewGetCompletePlanInternalServerError() *GetCompletePlanInternalServerError { + return &GetCompletePlanInternalServerError{} +} + +/*GetCompletePlanInternalServerError handles this case with default header values. + +unexpected error +*/ +type GetCompletePlanInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetCompletePlanInternalServerError) Error() string { + return fmt.Sprintf("[GET /plan/complete/{id}][%d] getCompletePlanInternalServerError %+v", 500, o.Payload) +} + +func (o *GetCompletePlanInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetCompletePlanInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/plan_management/get_plan_parameters.go b/services/plan-manager/client/plan_management/get_plan_parameters.go new file mode 100644 index 0000000..4df2004 --- /dev/null +++ b/services/plan-manager/client/plan_management/get_plan_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetPlanParams creates a new GetPlanParams object +// with the default values initialized. +func NewGetPlanParams() *GetPlanParams { + var () + return &GetPlanParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetPlanParamsWithTimeout creates a new GetPlanParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetPlanParamsWithTimeout(timeout time.Duration) *GetPlanParams { + var () + return &GetPlanParams{ + + timeout: timeout, + } +} + +// NewGetPlanParamsWithContext creates a new GetPlanParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetPlanParamsWithContext(ctx context.Context) *GetPlanParams { + var () + return &GetPlanParams{ + + Context: ctx, + } +} + +// NewGetPlanParamsWithHTTPClient creates a new GetPlanParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetPlanParamsWithHTTPClient(client *http.Client) *GetPlanParams { + var () + return &GetPlanParams{ + HTTPClient: client, + } +} + +/*GetPlanParams contains all the parameters to send to the API endpoint +for the get plan operation typically these are written to a http.Request +*/ +type GetPlanParams struct { + + /*ID + Id of plan to be obtained + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get plan params +func (o *GetPlanParams) WithTimeout(timeout time.Duration) *GetPlanParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get plan params +func (o *GetPlanParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get plan params +func (o *GetPlanParams) WithContext(ctx context.Context) *GetPlanParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get plan params +func (o *GetPlanParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get plan params +func (o *GetPlanParams) WithHTTPClient(client *http.Client) *GetPlanParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get plan params +func (o *GetPlanParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get plan params +func (o *GetPlanParams) WithID(id string) *GetPlanParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get plan params +func (o *GetPlanParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetPlanParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/plan_management/get_plan_responses.go b/services/plan-manager/client/plan_management/get_plan_responses.go new file mode 100644 index 0000000..c353b57 --- /dev/null +++ b/services/plan-manager/client/plan_management/get_plan_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetPlanReader is a Reader for the GetPlan structure. +type GetPlanReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetPlanReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetPlanOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetPlanNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetPlanInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetPlanOK creates a GetPlanOK with default headers values +func NewGetPlanOK() *GetPlanOK { + return &GetPlanOK{} +} + +/*GetPlanOK handles this case with default header values. + +plan returned +*/ +type GetPlanOK struct { + Payload *models.Plan +} + +func (o *GetPlanOK) Error() string { + return fmt.Sprintf("[GET /plan/{id}][%d] getPlanOK %+v", 200, o.Payload) +} + +func (o *GetPlanOK) GetPayload() *models.Plan { + return o.Payload +} + +func (o *GetPlanOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Plan) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetPlanNotFound creates a GetPlanNotFound with default headers values +func NewGetPlanNotFound() *GetPlanNotFound { + return &GetPlanNotFound{} +} + +/*GetPlanNotFound handles this case with default header values. + +plan with planid not found +*/ +type GetPlanNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetPlanNotFound) Error() string { + return fmt.Sprintf("[GET /plan/{id}][%d] getPlanNotFound %+v", 404, o.Payload) +} + +func (o *GetPlanNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetPlanNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetPlanInternalServerError creates a GetPlanInternalServerError with default headers values +func NewGetPlanInternalServerError() *GetPlanInternalServerError { + return &GetPlanInternalServerError{} +} + +/*GetPlanInternalServerError handles this case with default header values. + +unexpected error +*/ +type GetPlanInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetPlanInternalServerError) Error() string { + return fmt.Sprintf("[GET /plan/{id}][%d] getPlanInternalServerError %+v", 500, o.Payload) +} + +func (o *GetPlanInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetPlanInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/plan_management/list_complete_plans_parameters.go b/services/plan-manager/client/plan_management/list_complete_plans_parameters.go new file mode 100644 index 0000000..f552b97 --- /dev/null +++ b/services/plan-manager/client/plan_management/list_complete_plans_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListCompletePlansParams creates a new ListCompletePlansParams object +// with the default values initialized. +func NewListCompletePlansParams() *ListCompletePlansParams { + + return &ListCompletePlansParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListCompletePlansParamsWithTimeout creates a new ListCompletePlansParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListCompletePlansParamsWithTimeout(timeout time.Duration) *ListCompletePlansParams { + + return &ListCompletePlansParams{ + + timeout: timeout, + } +} + +// NewListCompletePlansParamsWithContext creates a new ListCompletePlansParams object +// with the default values initialized, and the ability to set a context for a request +func NewListCompletePlansParamsWithContext(ctx context.Context) *ListCompletePlansParams { + + return &ListCompletePlansParams{ + + Context: ctx, + } +} + +// NewListCompletePlansParamsWithHTTPClient creates a new ListCompletePlansParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListCompletePlansParamsWithHTTPClient(client *http.Client) *ListCompletePlansParams { + + return &ListCompletePlansParams{ + HTTPClient: client, + } +} + +/*ListCompletePlansParams contains all the parameters to send to the API endpoint +for the list complete plans operation typically these are written to a http.Request +*/ +type ListCompletePlansParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list complete plans params +func (o *ListCompletePlansParams) WithTimeout(timeout time.Duration) *ListCompletePlansParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list complete plans params +func (o *ListCompletePlansParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list complete plans params +func (o *ListCompletePlansParams) WithContext(ctx context.Context) *ListCompletePlansParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list complete plans params +func (o *ListCompletePlansParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list complete plans params +func (o *ListCompletePlansParams) WithHTTPClient(client *http.Client) *ListCompletePlansParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list complete plans params +func (o *ListCompletePlansParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListCompletePlansParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/plan_management/list_complete_plans_responses.go b/services/plan-manager/client/plan_management/list_complete_plans_responses.go new file mode 100644 index 0000000..4e56d88 --- /dev/null +++ b/services/plan-manager/client/plan_management/list_complete_plans_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListCompletePlansReader is a Reader for the ListCompletePlans structure. +type ListCompletePlansReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListCompletePlansReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListCompletePlansOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListCompletePlansInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListCompletePlansOK creates a ListCompletePlansOK with default headers values +func NewListCompletePlansOK() *ListCompletePlansOK { + return &ListCompletePlansOK{} +} + +/*ListCompletePlansOK handles this case with default header values. + +Set of known plans returned in full +*/ +type ListCompletePlansOK struct { + Payload []*models.Plan +} + +func (o *ListCompletePlansOK) Error() string { + return fmt.Sprintf("[GET /plan/complete][%d] listCompletePlansOK %+v", 200, o.Payload) +} + +func (o *ListCompletePlansOK) GetPayload() []*models.Plan { + return o.Payload +} + +func (o *ListCompletePlansOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListCompletePlansInternalServerError creates a ListCompletePlansInternalServerError with default headers values +func NewListCompletePlansInternalServerError() *ListCompletePlansInternalServerError { + return &ListCompletePlansInternalServerError{} +} + +/*ListCompletePlansInternalServerError handles this case with default header values. + +unexpected error +*/ +type ListCompletePlansInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListCompletePlansInternalServerError) Error() string { + return fmt.Sprintf("[GET /plan/complete][%d] listCompletePlansInternalServerError %+v", 500, o.Payload) +} + +func (o *ListCompletePlansInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListCompletePlansInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/plan_management/list_plans_parameters.go b/services/plan-manager/client/plan_management/list_plans_parameters.go new file mode 100644 index 0000000..4d9cb5b --- /dev/null +++ b/services/plan-manager/client/plan_management/list_plans_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListPlansParams creates a new ListPlansParams object +// with the default values initialized. +func NewListPlansParams() *ListPlansParams { + + return &ListPlansParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListPlansParamsWithTimeout creates a new ListPlansParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListPlansParamsWithTimeout(timeout time.Duration) *ListPlansParams { + + return &ListPlansParams{ + + timeout: timeout, + } +} + +// NewListPlansParamsWithContext creates a new ListPlansParams object +// with the default values initialized, and the ability to set a context for a request +func NewListPlansParamsWithContext(ctx context.Context) *ListPlansParams { + + return &ListPlansParams{ + + Context: ctx, + } +} + +// NewListPlansParamsWithHTTPClient creates a new ListPlansParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListPlansParamsWithHTTPClient(client *http.Client) *ListPlansParams { + + return &ListPlansParams{ + HTTPClient: client, + } +} + +/*ListPlansParams contains all the parameters to send to the API endpoint +for the list plans operation typically these are written to a http.Request +*/ +type ListPlansParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list plans params +func (o *ListPlansParams) WithTimeout(timeout time.Duration) *ListPlansParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list plans params +func (o *ListPlansParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list plans params +func (o *ListPlansParams) WithContext(ctx context.Context) *ListPlansParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list plans params +func (o *ListPlansParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list plans params +func (o *ListPlansParams) WithHTTPClient(client *http.Client) *ListPlansParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list plans params +func (o *ListPlansParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListPlansParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/plan_management/list_plans_responses.go b/services/plan-manager/client/plan_management/list_plans_responses.go new file mode 100644 index 0000000..2ded622 --- /dev/null +++ b/services/plan-manager/client/plan_management/list_plans_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListPlansReader is a Reader for the ListPlans structure. +type ListPlansReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListPlansReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListPlansOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListPlansInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListPlansOK creates a ListPlansOK with default headers values +func NewListPlansOK() *ListPlansOK { + return &ListPlansOK{} +} + +/*ListPlansOK handles this case with default header values. + +list of plans returned +*/ +type ListPlansOK struct { + Payload []*models.Plan +} + +func (o *ListPlansOK) Error() string { + return fmt.Sprintf("[GET /plan][%d] listPlansOK %+v", 200, o.Payload) +} + +func (o *ListPlansOK) GetPayload() []*models.Plan { + return o.Payload +} + +func (o *ListPlansOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListPlansInternalServerError creates a ListPlansInternalServerError with default headers values +func NewListPlansInternalServerError() *ListPlansInternalServerError { + return &ListPlansInternalServerError{} +} + +/*ListPlansInternalServerError handles this case with default header values. + +unexpected error +*/ +type ListPlansInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListPlansInternalServerError) Error() string { + return fmt.Sprintf("[GET /plan][%d] listPlansInternalServerError %+v", 500, o.Payload) +} + +func (o *ListPlansInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListPlansInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/plan_management/plan_management_client.go b/services/plan-manager/client/plan_management/plan_management_client.go new file mode 100644 index 0000000..1ce2fdb --- /dev/null +++ b/services/plan-manager/client/plan_management/plan_management_client.go @@ -0,0 +1,230 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the plan management client +type API interface { + /* + CreatePlan creates a plan + + Creates a new plan*/ + CreatePlan(ctx context.Context, params *CreatePlanParams) (*CreatePlanCreated, error) + /* + GetCompletePlan gets complete plan + + gets complete plan with planid*/ + GetCompletePlan(ctx context.Context, params *GetCompletePlanParams) (*GetCompletePlanOK, error) + /* + GetPlan gets specific plan + + get plan with given planid*/ + GetPlan(ctx context.Context, params *GetPlanParams) (*GetPlanOK, error) + /* + ListCompletePlans gets full information relating to known plans + + Obtains full information on all known plans*/ + ListCompletePlans(ctx context.Context, params *ListCompletePlansParams) (*ListCompletePlansOK, error) + /* + ListPlans lists all plans + + lists all plans (tbd - pagination?)*/ + ListPlans(ctx context.Context, params *ListPlansParams) (*ListPlansOK, error) + /* + UpdatePlan updates specific plan + + Update plan with given planId*/ + UpdatePlan(ctx context.Context, params *UpdatePlanParams) (*UpdatePlanOK, error) +} + +// New creates a new plan management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for plan management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +CreatePlan creates a plan + +Creates a new plan +*/ +func (a *Client) CreatePlan(ctx context.Context, params *CreatePlanParams) (*CreatePlanCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "createPlan", + Method: "POST", + PathPattern: "/plan", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &CreatePlanReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*CreatePlanCreated), nil + +} + +/* +GetCompletePlan gets complete plan + +gets complete plan with planid +*/ +func (a *Client) GetCompletePlan(ctx context.Context, params *GetCompletePlanParams) (*GetCompletePlanOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getCompletePlan", + Method: "GET", + PathPattern: "/plan/complete/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetCompletePlanReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetCompletePlanOK), nil + +} + +/* +GetPlan gets specific plan + +get plan with given planid +*/ +func (a *Client) GetPlan(ctx context.Context, params *GetPlanParams) (*GetPlanOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getPlan", + Method: "GET", + PathPattern: "/plan/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetPlanReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetPlanOK), nil + +} + +/* +ListCompletePlans gets full information relating to known plans + +Obtains full information on all known plans +*/ +func (a *Client) ListCompletePlans(ctx context.Context, params *ListCompletePlansParams) (*ListCompletePlansOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listCompletePlans", + Method: "GET", + PathPattern: "/plan/complete", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListCompletePlansReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListCompletePlansOK), nil + +} + +/* +ListPlans lists all plans + +lists all plans (tbd - pagination?) +*/ +func (a *Client) ListPlans(ctx context.Context, params *ListPlansParams) (*ListPlansOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listPlans", + Method: "GET", + PathPattern: "/plan", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListPlansReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListPlansOK), nil + +} + +/* +UpdatePlan updates specific plan + +Update plan with given planId +*/ +func (a *Client) UpdatePlan(ctx context.Context, params *UpdatePlanParams) (*UpdatePlanOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updatePlan", + Method: "PUT", + PathPattern: "/plan/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdatePlanReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UpdatePlanOK), nil + +} diff --git a/services/plan-manager/client/plan_management/update_plan_parameters.go b/services/plan-manager/client/plan_management/update_plan_parameters.go new file mode 100644 index 0000000..0baedce --- /dev/null +++ b/services/plan-manager/client/plan_management/update_plan_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdatePlanParams creates a new UpdatePlanParams object +// with the default values initialized. +func NewUpdatePlanParams() *UpdatePlanParams { + var () + return &UpdatePlanParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdatePlanParamsWithTimeout creates a new UpdatePlanParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdatePlanParamsWithTimeout(timeout time.Duration) *UpdatePlanParams { + var () + return &UpdatePlanParams{ + + timeout: timeout, + } +} + +// NewUpdatePlanParamsWithContext creates a new UpdatePlanParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdatePlanParamsWithContext(ctx context.Context) *UpdatePlanParams { + var () + return &UpdatePlanParams{ + + Context: ctx, + } +} + +// NewUpdatePlanParamsWithHTTPClient creates a new UpdatePlanParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdatePlanParamsWithHTTPClient(client *http.Client) *UpdatePlanParams { + var () + return &UpdatePlanParams{ + HTTPClient: client, + } +} + +/*UpdatePlanParams contains all the parameters to send to the API endpoint +for the update plan operation typically these are written to a http.Request +*/ +type UpdatePlanParams struct { + + /*ID + Id of plan to be obtained + + */ + ID string + /*Plan + updated plan containing all parameters except id + + */ + Plan *models.Plan + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update plan params +func (o *UpdatePlanParams) WithTimeout(timeout time.Duration) *UpdatePlanParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update plan params +func (o *UpdatePlanParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update plan params +func (o *UpdatePlanParams) WithContext(ctx context.Context) *UpdatePlanParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update plan params +func (o *UpdatePlanParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update plan params +func (o *UpdatePlanParams) WithHTTPClient(client *http.Client) *UpdatePlanParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update plan params +func (o *UpdatePlanParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the update plan params +func (o *UpdatePlanParams) WithID(id string) *UpdatePlanParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update plan params +func (o *UpdatePlanParams) SetID(id string) { + o.ID = id +} + +// WithPlan adds the plan to the update plan params +func (o *UpdatePlanParams) WithPlan(plan *models.Plan) *UpdatePlanParams { + o.SetPlan(plan) + return o +} + +// SetPlan adds the plan to the update plan params +func (o *UpdatePlanParams) SetPlan(plan *models.Plan) { + o.Plan = plan +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdatePlanParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Plan != nil { + if err := r.SetBodyParam(o.Plan); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/plan_management/update_plan_responses.go b/services/plan-manager/client/plan_management/update_plan_responses.go new file mode 100644 index 0000000..dd732b1 --- /dev/null +++ b/services/plan-manager/client/plan_management/update_plan_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdatePlanReader is a Reader for the UpdatePlan structure. +type UpdatePlanReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdatePlanReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdatePlanOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdatePlanNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdatePlanInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewUpdatePlanOK creates a UpdatePlanOK with default headers values +func NewUpdatePlanOK() *UpdatePlanOK { + return &UpdatePlanOK{} +} + +/*UpdatePlanOK handles this case with default header values. + +updated plan +*/ +type UpdatePlanOK struct { + Payload *models.Plan +} + +func (o *UpdatePlanOK) Error() string { + return fmt.Sprintf("[PUT /plan/{id}][%d] updatePlanOK %+v", 200, o.Payload) +} + +func (o *UpdatePlanOK) GetPayload() *models.Plan { + return o.Payload +} + +func (o *UpdatePlanOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Plan) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdatePlanNotFound creates a UpdatePlanNotFound with default headers values +func NewUpdatePlanNotFound() *UpdatePlanNotFound { + return &UpdatePlanNotFound{} +} + +/*UpdatePlanNotFound handles this case with default header values. + +plan with planid not found +*/ +type UpdatePlanNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdatePlanNotFound) Error() string { + return fmt.Sprintf("[PUT /plan/{id}][%d] updatePlanNotFound %+v", 404, o.Payload) +} + +func (o *UpdatePlanNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdatePlanNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdatePlanInternalServerError creates a UpdatePlanInternalServerError with default headers values +func NewUpdatePlanInternalServerError() *UpdatePlanInternalServerError { + return &UpdatePlanInternalServerError{} +} + +/*UpdatePlanInternalServerError handles this case with default header values. + +unexpected error +*/ +type UpdatePlanInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdatePlanInternalServerError) Error() string { + return fmt.Sprintf("[PUT /plan/{id}][%d] updatePlanInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdatePlanInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdatePlanInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/plan_manager_management_api_client.go b/services/plan-manager/client/plan_manager_management_api_client.go new file mode 100644 index 0000000..1c5a63e --- /dev/null +++ b/services/plan-manager/client/plan_manager_management_api_client.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/bundle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/cycle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/plan_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/price_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/sku_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/trigger_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v1.0" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new plan manager management API HTTP client. +func New(c Config) *PlanManagerManagementAPI { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(PlanManagerManagementAPI) + cli.Transport = transport + cli.BundleManagement = bundle_management.New(transport, strfmt.Default, c.AuthInfo) + cli.CycleManagement = cycle_management.New(transport, strfmt.Default, c.AuthInfo) + cli.PlanManagement = plan_management.New(transport, strfmt.Default, c.AuthInfo) + cli.PriceManagement = price_management.New(transport, strfmt.Default, c.AuthInfo) + cli.SkuManagement = sku_management.New(transport, strfmt.Default, c.AuthInfo) + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// PlanManagerManagementAPI is a client for plan manager management API +type PlanManagerManagementAPI struct { + BundleManagement *bundle_management.Client + CycleManagement *cycle_management.Client + PlanManagement *plan_management.Client + PriceManagement *price_management.Client + SkuManagement *sku_management.Client + StatusManagement *status_management.Client + TriggerManagement *trigger_management.Client + Transport runtime.ClientTransport +} diff --git a/services/plan-manager/client/price_management/create_sku_price_parameters.go b/services/plan-manager/client/price_management/create_sku_price_parameters.go new file mode 100644 index 0000000..4c65db8 --- /dev/null +++ b/services/plan-manager/client/price_management/create_sku_price_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateSkuPriceParams creates a new CreateSkuPriceParams object +// with the default values initialized. +func NewCreateSkuPriceParams() *CreateSkuPriceParams { + var () + return &CreateSkuPriceParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewCreateSkuPriceParamsWithTimeout creates a new CreateSkuPriceParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewCreateSkuPriceParamsWithTimeout(timeout time.Duration) *CreateSkuPriceParams { + var () + return &CreateSkuPriceParams{ + + timeout: timeout, + } +} + +// NewCreateSkuPriceParamsWithContext creates a new CreateSkuPriceParams object +// with the default values initialized, and the ability to set a context for a request +func NewCreateSkuPriceParamsWithContext(ctx context.Context) *CreateSkuPriceParams { + var () + return &CreateSkuPriceParams{ + + Context: ctx, + } +} + +// NewCreateSkuPriceParamsWithHTTPClient creates a new CreateSkuPriceParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewCreateSkuPriceParamsWithHTTPClient(client *http.Client) *CreateSkuPriceParams { + var () + return &CreateSkuPriceParams{ + HTTPClient: client, + } +} + +/*CreateSkuPriceParams contains all the parameters to send to the API endpoint +for the create sku price operation typically these are written to a http.Request +*/ +type CreateSkuPriceParams struct { + + /*Price + SKU price to be added + + */ + Price *models.SkuPrice + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the create sku price params +func (o *CreateSkuPriceParams) WithTimeout(timeout time.Duration) *CreateSkuPriceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create sku price params +func (o *CreateSkuPriceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create sku price params +func (o *CreateSkuPriceParams) WithContext(ctx context.Context) *CreateSkuPriceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create sku price params +func (o *CreateSkuPriceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create sku price params +func (o *CreateSkuPriceParams) WithHTTPClient(client *http.Client) *CreateSkuPriceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create sku price params +func (o *CreateSkuPriceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithPrice adds the price to the create sku price params +func (o *CreateSkuPriceParams) WithPrice(price *models.SkuPrice) *CreateSkuPriceParams { + o.SetPrice(price) + return o +} + +// SetPrice adds the price to the create sku price params +func (o *CreateSkuPriceParams) SetPrice(price *models.SkuPrice) { + o.Price = price +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateSkuPriceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Price != nil { + if err := r.SetBodyParam(o.Price); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/price_management/create_sku_price_responses.go b/services/plan-manager/client/price_management/create_sku_price_responses.go new file mode 100644 index 0000000..790bb28 --- /dev/null +++ b/services/plan-manager/client/price_management/create_sku_price_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateSkuPriceReader is a Reader for the CreateSkuPrice structure. +type CreateSkuPriceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateSkuPriceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewCreateSkuPriceCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewCreateSkuPriceBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewCreateSkuPriceConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewCreateSkuPriceInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewCreateSkuPriceCreated creates a CreateSkuPriceCreated with default headers values +func NewCreateSkuPriceCreated() *CreateSkuPriceCreated { + return &CreateSkuPriceCreated{} +} + +/*CreateSkuPriceCreated handles this case with default header values. + +item created +*/ +type CreateSkuPriceCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *CreateSkuPriceCreated) Error() string { + return fmt.Sprintf("[POST /sku/price][%d] createSkuPriceCreated %+v", 201, o.Payload) +} + +func (o *CreateSkuPriceCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *CreateSkuPriceCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateSkuPriceBadRequest creates a CreateSkuPriceBadRequest with default headers values +func NewCreateSkuPriceBadRequest() *CreateSkuPriceBadRequest { + return &CreateSkuPriceBadRequest{} +} + +/*CreateSkuPriceBadRequest handles this case with default header values. + +invalid input, object invalid +*/ +type CreateSkuPriceBadRequest struct { +} + +func (o *CreateSkuPriceBadRequest) Error() string { + return fmt.Sprintf("[POST /sku/price][%d] createSkuPriceBadRequest ", 400) +} + +func (o *CreateSkuPriceBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewCreateSkuPriceConflict creates a CreateSkuPriceConflict with default headers values +func NewCreateSkuPriceConflict() *CreateSkuPriceConflict { + return &CreateSkuPriceConflict{} +} + +/*CreateSkuPriceConflict handles this case with default header values. + +an existing item already exists +*/ +type CreateSkuPriceConflict struct { + Payload *models.ErrorResponse +} + +func (o *CreateSkuPriceConflict) Error() string { + return fmt.Sprintf("[POST /sku/price][%d] createSkuPriceConflict %+v", 409, o.Payload) +} + +func (o *CreateSkuPriceConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateSkuPriceConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateSkuPriceInternalServerError creates a CreateSkuPriceInternalServerError with default headers values +func NewCreateSkuPriceInternalServerError() *CreateSkuPriceInternalServerError { + return &CreateSkuPriceInternalServerError{} +} + +/*CreateSkuPriceInternalServerError handles this case with default header values. + +unexpected error +*/ +type CreateSkuPriceInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *CreateSkuPriceInternalServerError) Error() string { + return fmt.Sprintf("[POST /sku/price][%d] createSkuPriceInternalServerError %+v", 500, o.Payload) +} + +func (o *CreateSkuPriceInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateSkuPriceInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/price_management/get_sku_price_parameters.go b/services/plan-manager/client/price_management/get_sku_price_parameters.go new file mode 100644 index 0000000..101cdd4 --- /dev/null +++ b/services/plan-manager/client/price_management/get_sku_price_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuPriceParams creates a new GetSkuPriceParams object +// with the default values initialized. +func NewGetSkuPriceParams() *GetSkuPriceParams { + var () + return &GetSkuPriceParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSkuPriceParamsWithTimeout creates a new GetSkuPriceParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSkuPriceParamsWithTimeout(timeout time.Duration) *GetSkuPriceParams { + var () + return &GetSkuPriceParams{ + + timeout: timeout, + } +} + +// NewGetSkuPriceParamsWithContext creates a new GetSkuPriceParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSkuPriceParamsWithContext(ctx context.Context) *GetSkuPriceParams { + var () + return &GetSkuPriceParams{ + + Context: ctx, + } +} + +// NewGetSkuPriceParamsWithHTTPClient creates a new GetSkuPriceParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSkuPriceParamsWithHTTPClient(client *http.Client) *GetSkuPriceParams { + var () + return &GetSkuPriceParams{ + HTTPClient: client, + } +} + +/*GetSkuPriceParams contains all the parameters to send to the API endpoint +for the get sku price operation typically these are written to a http.Request +*/ +type GetSkuPriceParams struct { + + /*ID + Id of sku price to be obtained + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get sku price params +func (o *GetSkuPriceParams) WithTimeout(timeout time.Duration) *GetSkuPriceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get sku price params +func (o *GetSkuPriceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get sku price params +func (o *GetSkuPriceParams) WithContext(ctx context.Context) *GetSkuPriceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get sku price params +func (o *GetSkuPriceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get sku price params +func (o *GetSkuPriceParams) WithHTTPClient(client *http.Client) *GetSkuPriceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get sku price params +func (o *GetSkuPriceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get sku price params +func (o *GetSkuPriceParams) WithID(id string) *GetSkuPriceParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get sku price params +func (o *GetSkuPriceParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSkuPriceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/price_management/get_sku_price_responses.go b/services/plan-manager/client/price_management/get_sku_price_responses.go new file mode 100644 index 0000000..4d77495 --- /dev/null +++ b/services/plan-manager/client/price_management/get_sku_price_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuPriceReader is a Reader for the GetSkuPrice structure. +type GetSkuPriceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSkuPriceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSkuPriceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetSkuPriceNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetSkuPriceInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetSkuPriceOK creates a GetSkuPriceOK with default headers values +func NewGetSkuPriceOK() *GetSkuPriceOK { + return &GetSkuPriceOK{} +} + +/*GetSkuPriceOK handles this case with default header values. + +sku price returned +*/ +type GetSkuPriceOK struct { + Payload *models.SkuPrice +} + +func (o *GetSkuPriceOK) Error() string { + return fmt.Sprintf("[GET /sku/price/{id}][%d] getSkuPriceOK %+v", 200, o.Payload) +} + +func (o *GetSkuPriceOK) GetPayload() *models.SkuPrice { + return o.Payload +} + +func (o *GetSkuPriceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SkuPrice) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuPriceNotFound creates a GetSkuPriceNotFound with default headers values +func NewGetSkuPriceNotFound() *GetSkuPriceNotFound { + return &GetSkuPriceNotFound{} +} + +/*GetSkuPriceNotFound handles this case with default header values. + +sku price with skupriceid not found +*/ +type GetSkuPriceNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuPriceNotFound) Error() string { + return fmt.Sprintf("[GET /sku/price/{id}][%d] getSkuPriceNotFound %+v", 404, o.Payload) +} + +func (o *GetSkuPriceNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuPriceNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuPriceInternalServerError creates a GetSkuPriceInternalServerError with default headers values +func NewGetSkuPriceInternalServerError() *GetSkuPriceInternalServerError { + return &GetSkuPriceInternalServerError{} +} + +/*GetSkuPriceInternalServerError handles this case with default header values. + +unexpected error +*/ +type GetSkuPriceInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuPriceInternalServerError) Error() string { + return fmt.Sprintf("[GET /sku/price/{id}][%d] getSkuPriceInternalServerError %+v", 500, o.Payload) +} + +func (o *GetSkuPriceInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuPriceInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/price_management/list_sku_prices_parameters.go b/services/plan-manager/client/price_management/list_sku_prices_parameters.go new file mode 100644 index 0000000..00b4599 --- /dev/null +++ b/services/plan-manager/client/price_management/list_sku_prices_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListSkuPricesParams creates a new ListSkuPricesParams object +// with the default values initialized. +func NewListSkuPricesParams() *ListSkuPricesParams { + + return &ListSkuPricesParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListSkuPricesParamsWithTimeout creates a new ListSkuPricesParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListSkuPricesParamsWithTimeout(timeout time.Duration) *ListSkuPricesParams { + + return &ListSkuPricesParams{ + + timeout: timeout, + } +} + +// NewListSkuPricesParamsWithContext creates a new ListSkuPricesParams object +// with the default values initialized, and the ability to set a context for a request +func NewListSkuPricesParamsWithContext(ctx context.Context) *ListSkuPricesParams { + + return &ListSkuPricesParams{ + + Context: ctx, + } +} + +// NewListSkuPricesParamsWithHTTPClient creates a new ListSkuPricesParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListSkuPricesParamsWithHTTPClient(client *http.Client) *ListSkuPricesParams { + + return &ListSkuPricesParams{ + HTTPClient: client, + } +} + +/*ListSkuPricesParams contains all the parameters to send to the API endpoint +for the list sku prices operation typically these are written to a http.Request +*/ +type ListSkuPricesParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list sku prices params +func (o *ListSkuPricesParams) WithTimeout(timeout time.Duration) *ListSkuPricesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list sku prices params +func (o *ListSkuPricesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list sku prices params +func (o *ListSkuPricesParams) WithContext(ctx context.Context) *ListSkuPricesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list sku prices params +func (o *ListSkuPricesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list sku prices params +func (o *ListSkuPricesParams) WithHTTPClient(client *http.Client) *ListSkuPricesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list sku prices params +func (o *ListSkuPricesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListSkuPricesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/price_management/list_sku_prices_responses.go b/services/plan-manager/client/price_management/list_sku_prices_responses.go new file mode 100644 index 0000000..a6f8802 --- /dev/null +++ b/services/plan-manager/client/price_management/list_sku_prices_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListSkuPricesReader is a Reader for the ListSkuPrices structure. +type ListSkuPricesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListSkuPricesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListSkuPricesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListSkuPricesInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListSkuPricesOK creates a ListSkuPricesOK with default headers values +func NewListSkuPricesOK() *ListSkuPricesOK { + return &ListSkuPricesOK{} +} + +/*ListSkuPricesOK handles this case with default header values. + +list of skus prices returned +*/ +type ListSkuPricesOK struct { + Payload []*models.SkuPrice +} + +func (o *ListSkuPricesOK) Error() string { + return fmt.Sprintf("[GET /sku/price][%d] listSkuPricesOK %+v", 200, o.Payload) +} + +func (o *ListSkuPricesOK) GetPayload() []*models.SkuPrice { + return o.Payload +} + +func (o *ListSkuPricesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListSkuPricesInternalServerError creates a ListSkuPricesInternalServerError with default headers values +func NewListSkuPricesInternalServerError() *ListSkuPricesInternalServerError { + return &ListSkuPricesInternalServerError{} +} + +/*ListSkuPricesInternalServerError handles this case with default header values. + +unexpected error +*/ +type ListSkuPricesInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListSkuPricesInternalServerError) Error() string { + return fmt.Sprintf("[GET /sku/price][%d] listSkuPricesInternalServerError %+v", 500, o.Payload) +} + +func (o *ListSkuPricesInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListSkuPricesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/price_management/price_management_client.go b/services/plan-manager/client/price_management/price_management_client.go new file mode 100644 index 0000000..0b0eefe --- /dev/null +++ b/services/plan-manager/client/price_management/price_management_client.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the price management client +type API interface { + /* + CreateSkuPrice creates s k u price + + Creates a new sku price*/ + CreateSkuPrice(ctx context.Context, params *CreateSkuPriceParams) (*CreateSkuPriceCreated, error) + /* + GetSkuPrice gets specific sku price + + get sku price with given skupriceid*/ + GetSkuPrice(ctx context.Context, params *GetSkuPriceParams) (*GetSkuPriceOK, error) + /* + ListSkuPrices lists s k u prices + + lists all sku prices*/ + ListSkuPrices(ctx context.Context, params *ListSkuPricesParams) (*ListSkuPricesOK, error) + /* + UpdateSkuPrice updates specific sku price + + Update sku price with given skupriceid*/ + UpdateSkuPrice(ctx context.Context, params *UpdateSkuPriceParams) (*UpdateSkuPriceOK, error) +} + +// New creates a new price management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for price management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +CreateSkuPrice creates s k u price + +Creates a new sku price +*/ +func (a *Client) CreateSkuPrice(ctx context.Context, params *CreateSkuPriceParams) (*CreateSkuPriceCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "createSkuPrice", + Method: "POST", + PathPattern: "/sku/price", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &CreateSkuPriceReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*CreateSkuPriceCreated), nil + +} + +/* +GetSkuPrice gets specific sku price + +get sku price with given skupriceid +*/ +func (a *Client) GetSkuPrice(ctx context.Context, params *GetSkuPriceParams) (*GetSkuPriceOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSkuPrice", + Method: "GET", + PathPattern: "/sku/price/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSkuPriceReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSkuPriceOK), nil + +} + +/* +ListSkuPrices lists s k u prices + +lists all sku prices +*/ +func (a *Client) ListSkuPrices(ctx context.Context, params *ListSkuPricesParams) (*ListSkuPricesOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listSkuPrices", + Method: "GET", + PathPattern: "/sku/price", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListSkuPricesReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListSkuPricesOK), nil + +} + +/* +UpdateSkuPrice updates specific sku price + +Update sku price with given skupriceid +*/ +func (a *Client) UpdateSkuPrice(ctx context.Context, params *UpdateSkuPriceParams) (*UpdateSkuPriceOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updateSkuPrice", + Method: "PUT", + PathPattern: "/sku/price/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdateSkuPriceReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UpdateSkuPriceOK), nil + +} diff --git a/services/plan-manager/client/price_management/update_sku_price_parameters.go b/services/plan-manager/client/price_management/update_sku_price_parameters.go new file mode 100644 index 0000000..67cd1e6 --- /dev/null +++ b/services/plan-manager/client/price_management/update_sku_price_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateSkuPriceParams creates a new UpdateSkuPriceParams object +// with the default values initialized. +func NewUpdateSkuPriceParams() *UpdateSkuPriceParams { + var () + return &UpdateSkuPriceParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateSkuPriceParamsWithTimeout creates a new UpdateSkuPriceParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdateSkuPriceParamsWithTimeout(timeout time.Duration) *UpdateSkuPriceParams { + var () + return &UpdateSkuPriceParams{ + + timeout: timeout, + } +} + +// NewUpdateSkuPriceParamsWithContext creates a new UpdateSkuPriceParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdateSkuPriceParamsWithContext(ctx context.Context) *UpdateSkuPriceParams { + var () + return &UpdateSkuPriceParams{ + + Context: ctx, + } +} + +// NewUpdateSkuPriceParamsWithHTTPClient creates a new UpdateSkuPriceParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdateSkuPriceParamsWithHTTPClient(client *http.Client) *UpdateSkuPriceParams { + var () + return &UpdateSkuPriceParams{ + HTTPClient: client, + } +} + +/*UpdateSkuPriceParams contains all the parameters to send to the API endpoint +for the update sku price operation typically these are written to a http.Request +*/ +type UpdateSkuPriceParams struct { + + /*ID + Id of sku price to be obtained + + */ + ID string + /*Price + updated sku containing all parameters except id + + */ + Price *models.SkuPrice + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update sku price params +func (o *UpdateSkuPriceParams) WithTimeout(timeout time.Duration) *UpdateSkuPriceParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update sku price params +func (o *UpdateSkuPriceParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update sku price params +func (o *UpdateSkuPriceParams) WithContext(ctx context.Context) *UpdateSkuPriceParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update sku price params +func (o *UpdateSkuPriceParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update sku price params +func (o *UpdateSkuPriceParams) WithHTTPClient(client *http.Client) *UpdateSkuPriceParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update sku price params +func (o *UpdateSkuPriceParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the update sku price params +func (o *UpdateSkuPriceParams) WithID(id string) *UpdateSkuPriceParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update sku price params +func (o *UpdateSkuPriceParams) SetID(id string) { + o.ID = id +} + +// WithPrice adds the price to the update sku price params +func (o *UpdateSkuPriceParams) WithPrice(price *models.SkuPrice) *UpdateSkuPriceParams { + o.SetPrice(price) + return o +} + +// SetPrice adds the price to the update sku price params +func (o *UpdateSkuPriceParams) SetPrice(price *models.SkuPrice) { + o.Price = price +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateSkuPriceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Price != nil { + if err := r.SetBodyParam(o.Price); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/price_management/update_sku_price_responses.go b/services/plan-manager/client/price_management/update_sku_price_responses.go new file mode 100644 index 0000000..30092b7 --- /dev/null +++ b/services/plan-manager/client/price_management/update_sku_price_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateSkuPriceReader is a Reader for the UpdateSkuPrice structure. +type UpdateSkuPriceReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateSkuPriceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateSkuPriceOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdateSkuPriceNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdateSkuPriceInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewUpdateSkuPriceOK creates a UpdateSkuPriceOK with default headers values +func NewUpdateSkuPriceOK() *UpdateSkuPriceOK { + return &UpdateSkuPriceOK{} +} + +/*UpdateSkuPriceOK handles this case with default header values. + +updated sku price +*/ +type UpdateSkuPriceOK struct { + Payload *models.SkuPrice +} + +func (o *UpdateSkuPriceOK) Error() string { + return fmt.Sprintf("[PUT /sku/price/{id}][%d] updateSkuPriceOK %+v", 200, o.Payload) +} + +func (o *UpdateSkuPriceOK) GetPayload() *models.SkuPrice { + return o.Payload +} + +func (o *UpdateSkuPriceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SkuPrice) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateSkuPriceNotFound creates a UpdateSkuPriceNotFound with default headers values +func NewUpdateSkuPriceNotFound() *UpdateSkuPriceNotFound { + return &UpdateSkuPriceNotFound{} +} + +/*UpdateSkuPriceNotFound handles this case with default header values. + +sku price with skupriceid not found +*/ +type UpdateSkuPriceNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdateSkuPriceNotFound) Error() string { + return fmt.Sprintf("[PUT /sku/price/{id}][%d] updateSkuPriceNotFound %+v", 404, o.Payload) +} + +func (o *UpdateSkuPriceNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateSkuPriceNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateSkuPriceInternalServerError creates a UpdateSkuPriceInternalServerError with default headers values +func NewUpdateSkuPriceInternalServerError() *UpdateSkuPriceInternalServerError { + return &UpdateSkuPriceInternalServerError{} +} + +/*UpdateSkuPriceInternalServerError handles this case with default header values. + +unexpected error +*/ +type UpdateSkuPriceInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdateSkuPriceInternalServerError) Error() string { + return fmt.Sprintf("[PUT /sku/price/{id}][%d] updateSkuPriceInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdateSkuPriceInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateSkuPriceInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/sku_management/create_sku_parameters.go b/services/plan-manager/client/sku_management/create_sku_parameters.go new file mode 100644 index 0000000..3458528 --- /dev/null +++ b/services/plan-manager/client/sku_management/create_sku_parameters.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateSkuParams creates a new CreateSkuParams object +// with the default values initialized. +func NewCreateSkuParams() *CreateSkuParams { + var () + return &CreateSkuParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewCreateSkuParamsWithTimeout creates a new CreateSkuParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewCreateSkuParamsWithTimeout(timeout time.Duration) *CreateSkuParams { + var () + return &CreateSkuParams{ + + timeout: timeout, + } +} + +// NewCreateSkuParamsWithContext creates a new CreateSkuParams object +// with the default values initialized, and the ability to set a context for a request +func NewCreateSkuParamsWithContext(ctx context.Context) *CreateSkuParams { + var () + return &CreateSkuParams{ + + Context: ctx, + } +} + +// NewCreateSkuParamsWithHTTPClient creates a new CreateSkuParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewCreateSkuParamsWithHTTPClient(client *http.Client) *CreateSkuParams { + var () + return &CreateSkuParams{ + HTTPClient: client, + } +} + +/*CreateSkuParams contains all the parameters to send to the API endpoint +for the create sku operation typically these are written to a http.Request +*/ +type CreateSkuParams struct { + + /*Sku + SKU to be added + + */ + Sku *models.Sku + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the create sku params +func (o *CreateSkuParams) WithTimeout(timeout time.Duration) *CreateSkuParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the create sku params +func (o *CreateSkuParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the create sku params +func (o *CreateSkuParams) WithContext(ctx context.Context) *CreateSkuParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the create sku params +func (o *CreateSkuParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the create sku params +func (o *CreateSkuParams) WithHTTPClient(client *http.Client) *CreateSkuParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the create sku params +func (o *CreateSkuParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSku adds the sku to the create sku params +func (o *CreateSkuParams) WithSku(sku *models.Sku) *CreateSkuParams { + o.SetSku(sku) + return o +} + +// SetSku adds the sku to the create sku params +func (o *CreateSkuParams) SetSku(sku *models.Sku) { + o.Sku = sku +} + +// WriteToRequest writes these params to a swagger request +func (o *CreateSkuParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Sku != nil { + if err := r.SetBodyParam(o.Sku); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/sku_management/create_sku_responses.go b/services/plan-manager/client/sku_management/create_sku_responses.go new file mode 100644 index 0000000..5c0f6cb --- /dev/null +++ b/services/plan-manager/client/sku_management/create_sku_responses.go @@ -0,0 +1,174 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateSkuReader is a Reader for the CreateSku structure. +type CreateSkuReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *CreateSkuReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 201: + result := NewCreateSkuCreated() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewCreateSkuBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 409: + result := NewCreateSkuConflict() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewCreateSkuInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewCreateSkuCreated creates a CreateSkuCreated with default headers values +func NewCreateSkuCreated() *CreateSkuCreated { + return &CreateSkuCreated{} +} + +/*CreateSkuCreated handles this case with default header values. + +item created +*/ +type CreateSkuCreated struct { + Payload *models.ItemCreatedResponse +} + +func (o *CreateSkuCreated) Error() string { + return fmt.Sprintf("[POST /sku][%d] createSkuCreated %+v", 201, o.Payload) +} + +func (o *CreateSkuCreated) GetPayload() *models.ItemCreatedResponse { + return o.Payload +} + +func (o *CreateSkuCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ItemCreatedResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateSkuBadRequest creates a CreateSkuBadRequest with default headers values +func NewCreateSkuBadRequest() *CreateSkuBadRequest { + return &CreateSkuBadRequest{} +} + +/*CreateSkuBadRequest handles this case with default header values. + +invalid input, object invalid +*/ +type CreateSkuBadRequest struct { +} + +func (o *CreateSkuBadRequest) Error() string { + return fmt.Sprintf("[POST /sku][%d] createSkuBadRequest ", 400) +} + +func (o *CreateSkuBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewCreateSkuConflict creates a CreateSkuConflict with default headers values +func NewCreateSkuConflict() *CreateSkuConflict { + return &CreateSkuConflict{} +} + +/*CreateSkuConflict handles this case with default header values. + +an existing item already exists +*/ +type CreateSkuConflict struct { + Payload *models.ErrorResponse +} + +func (o *CreateSkuConflict) Error() string { + return fmt.Sprintf("[POST /sku][%d] createSkuConflict %+v", 409, o.Payload) +} + +func (o *CreateSkuConflict) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateSkuConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewCreateSkuInternalServerError creates a CreateSkuInternalServerError with default headers values +func NewCreateSkuInternalServerError() *CreateSkuInternalServerError { + return &CreateSkuInternalServerError{} +} + +/*CreateSkuInternalServerError handles this case with default header values. + +unexpected error +*/ +type CreateSkuInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *CreateSkuInternalServerError) Error() string { + return fmt.Sprintf("[POST /sku][%d] createSkuInternalServerError %+v", 500, o.Payload) +} + +func (o *CreateSkuInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *CreateSkuInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/sku_management/get_sku_parameters.go b/services/plan-manager/client/sku_management/get_sku_parameters.go new file mode 100644 index 0000000..1767247 --- /dev/null +++ b/services/plan-manager/client/sku_management/get_sku_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuParams creates a new GetSkuParams object +// with the default values initialized. +func NewGetSkuParams() *GetSkuParams { + var () + return &GetSkuParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSkuParamsWithTimeout creates a new GetSkuParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSkuParamsWithTimeout(timeout time.Duration) *GetSkuParams { + var () + return &GetSkuParams{ + + timeout: timeout, + } +} + +// NewGetSkuParamsWithContext creates a new GetSkuParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSkuParamsWithContext(ctx context.Context) *GetSkuParams { + var () + return &GetSkuParams{ + + Context: ctx, + } +} + +// NewGetSkuParamsWithHTTPClient creates a new GetSkuParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSkuParamsWithHTTPClient(client *http.Client) *GetSkuParams { + var () + return &GetSkuParams{ + HTTPClient: client, + } +} + +/*GetSkuParams contains all the parameters to send to the API endpoint +for the get sku operation typically these are written to a http.Request +*/ +type GetSkuParams struct { + + /*ID + Id of sku to be obtained + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get sku params +func (o *GetSkuParams) WithTimeout(timeout time.Duration) *GetSkuParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get sku params +func (o *GetSkuParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get sku params +func (o *GetSkuParams) WithContext(ctx context.Context) *GetSkuParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get sku params +func (o *GetSkuParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get sku params +func (o *GetSkuParams) WithHTTPClient(client *http.Client) *GetSkuParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get sku params +func (o *GetSkuParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get sku params +func (o *GetSkuParams) WithID(id string) *GetSkuParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get sku params +func (o *GetSkuParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSkuParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/sku_management/get_sku_responses.go b/services/plan-manager/client/sku_management/get_sku_responses.go new file mode 100644 index 0000000..b4cc6ce --- /dev/null +++ b/services/plan-manager/client/sku_management/get_sku_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuReader is a Reader for the GetSku structure. +type GetSkuReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSkuReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSkuOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetSkuNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewGetSkuInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetSkuOK creates a GetSkuOK with default headers values +func NewGetSkuOK() *GetSkuOK { + return &GetSkuOK{} +} + +/*GetSkuOK handles this case with default header values. + +sku returned +*/ +type GetSkuOK struct { + Payload *models.Sku +} + +func (o *GetSkuOK) Error() string { + return fmt.Sprintf("[GET /sku/{id}][%d] getSkuOK %+v", 200, o.Payload) +} + +func (o *GetSkuOK) GetPayload() *models.Sku { + return o.Payload +} + +func (o *GetSkuOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Sku) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuNotFound creates a GetSkuNotFound with default headers values +func NewGetSkuNotFound() *GetSkuNotFound { + return &GetSkuNotFound{} +} + +/*GetSkuNotFound handles this case with default header values. + +sku with skuid not found +*/ +type GetSkuNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuNotFound) Error() string { + return fmt.Sprintf("[GET /sku/{id}][%d] getSkuNotFound %+v", 404, o.Payload) +} + +func (o *GetSkuNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSkuInternalServerError creates a GetSkuInternalServerError with default headers values +func NewGetSkuInternalServerError() *GetSkuInternalServerError { + return &GetSkuInternalServerError{} +} + +/*GetSkuInternalServerError handles this case with default header values. + +unexpected error +*/ +type GetSkuInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetSkuInternalServerError) Error() string { + return fmt.Sprintf("[GET /sku/{id}][%d] getSkuInternalServerError %+v", 500, o.Payload) +} + +func (o *GetSkuInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSkuInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/sku_management/list_skus_parameters.go b/services/plan-manager/client/sku_management/list_skus_parameters.go new file mode 100644 index 0000000..851e9bb --- /dev/null +++ b/services/plan-manager/client/sku_management/list_skus_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewListSkusParams creates a new ListSkusParams object +// with the default values initialized. +func NewListSkusParams() *ListSkusParams { + + return &ListSkusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewListSkusParamsWithTimeout creates a new ListSkusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewListSkusParamsWithTimeout(timeout time.Duration) *ListSkusParams { + + return &ListSkusParams{ + + timeout: timeout, + } +} + +// NewListSkusParamsWithContext creates a new ListSkusParams object +// with the default values initialized, and the ability to set a context for a request +func NewListSkusParamsWithContext(ctx context.Context) *ListSkusParams { + + return &ListSkusParams{ + + Context: ctx, + } +} + +// NewListSkusParamsWithHTTPClient creates a new ListSkusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewListSkusParamsWithHTTPClient(client *http.Client) *ListSkusParams { + + return &ListSkusParams{ + HTTPClient: client, + } +} + +/*ListSkusParams contains all the parameters to send to the API endpoint +for the list skus operation typically these are written to a http.Request +*/ +type ListSkusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the list skus params +func (o *ListSkusParams) WithTimeout(timeout time.Duration) *ListSkusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the list skus params +func (o *ListSkusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the list skus params +func (o *ListSkusParams) WithContext(ctx context.Context) *ListSkusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the list skus params +func (o *ListSkusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the list skus params +func (o *ListSkusParams) WithHTTPClient(client *http.Client) *ListSkusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the list skus params +func (o *ListSkusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ListSkusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/sku_management/list_skus_responses.go b/services/plan-manager/client/sku_management/list_skus_responses.go new file mode 100644 index 0000000..92af203 --- /dev/null +++ b/services/plan-manager/client/sku_management/list_skus_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListSkusReader is a Reader for the ListSkus structure. +type ListSkusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ListSkusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewListSkusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewListSkusInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewListSkusOK creates a ListSkusOK with default headers values +func NewListSkusOK() *ListSkusOK { + return &ListSkusOK{} +} + +/*ListSkusOK handles this case with default header values. + +list of skus returned +*/ +type ListSkusOK struct { + Payload []*models.Sku +} + +func (o *ListSkusOK) Error() string { + return fmt.Sprintf("[GET /sku][%d] listSkusOK %+v", 200, o.Payload) +} + +func (o *ListSkusOK) GetPayload() []*models.Sku { + return o.Payload +} + +func (o *ListSkusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewListSkusInternalServerError creates a ListSkusInternalServerError with default headers values +func NewListSkusInternalServerError() *ListSkusInternalServerError { + return &ListSkusInternalServerError{} +} + +/*ListSkusInternalServerError handles this case with default header values. + +unexpected error +*/ +type ListSkusInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ListSkusInternalServerError) Error() string { + return fmt.Sprintf("[GET /sku][%d] listSkusInternalServerError %+v", 500, o.Payload) +} + +func (o *ListSkusInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ListSkusInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/sku_management/sku_management_client.go b/services/plan-manager/client/sku_management/sku_management_client.go new file mode 100644 index 0000000..ed2d1d0 --- /dev/null +++ b/services/plan-manager/client/sku_management/sku_management_client.go @@ -0,0 +1,166 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the sku management client +type API interface { + /* + CreateSku creates s k u + + Creates a new sku*/ + CreateSku(ctx context.Context, params *CreateSkuParams) (*CreateSkuCreated, error) + /* + GetSku gets specific sku + + get sku with given skuid*/ + GetSku(ctx context.Context, params *GetSkuParams) (*GetSkuOK, error) + /* + ListSkus lists s k us + + lists all skus*/ + ListSkus(ctx context.Context, params *ListSkusParams) (*ListSkusOK, error) + /* + UpdateSku updates specific sku + + Update sku with given skuid*/ + UpdateSku(ctx context.Context, params *UpdateSkuParams) (*UpdateSkuOK, error) +} + +// New creates a new sku management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for sku management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +CreateSku creates s k u + +Creates a new sku +*/ +func (a *Client) CreateSku(ctx context.Context, params *CreateSkuParams) (*CreateSkuCreated, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "createSku", + Method: "POST", + PathPattern: "/sku", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &CreateSkuReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*CreateSkuCreated), nil + +} + +/* +GetSku gets specific sku + +get sku with given skuid +*/ +func (a *Client) GetSku(ctx context.Context, params *GetSkuParams) (*GetSkuOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSku", + Method: "GET", + PathPattern: "/sku/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSkuReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSkuOK), nil + +} + +/* +ListSkus lists s k us + +lists all skus +*/ +func (a *Client) ListSkus(ctx context.Context, params *ListSkusParams) (*ListSkusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "listSkus", + Method: "GET", + PathPattern: "/sku", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ListSkusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ListSkusOK), nil + +} + +/* +UpdateSku updates specific sku + +Update sku with given skuid +*/ +func (a *Client) UpdateSku(ctx context.Context, params *UpdateSkuParams) (*UpdateSkuOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "updateSku", + Method: "PUT", + PathPattern: "/sku/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &UpdateSkuReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*UpdateSkuOK), nil + +} diff --git a/services/plan-manager/client/sku_management/update_sku_parameters.go b/services/plan-manager/client/sku_management/update_sku_parameters.go new file mode 100644 index 0000000..f6e6fef --- /dev/null +++ b/services/plan-manager/client/sku_management/update_sku_parameters.go @@ -0,0 +1,159 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateSkuParams creates a new UpdateSkuParams object +// with the default values initialized. +func NewUpdateSkuParams() *UpdateSkuParams { + var () + return &UpdateSkuParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewUpdateSkuParamsWithTimeout creates a new UpdateSkuParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewUpdateSkuParamsWithTimeout(timeout time.Duration) *UpdateSkuParams { + var () + return &UpdateSkuParams{ + + timeout: timeout, + } +} + +// NewUpdateSkuParamsWithContext creates a new UpdateSkuParams object +// with the default values initialized, and the ability to set a context for a request +func NewUpdateSkuParamsWithContext(ctx context.Context) *UpdateSkuParams { + var () + return &UpdateSkuParams{ + + Context: ctx, + } +} + +// NewUpdateSkuParamsWithHTTPClient creates a new UpdateSkuParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewUpdateSkuParamsWithHTTPClient(client *http.Client) *UpdateSkuParams { + var () + return &UpdateSkuParams{ + HTTPClient: client, + } +} + +/*UpdateSkuParams contains all the parameters to send to the API endpoint +for the update sku operation typically these are written to a http.Request +*/ +type UpdateSkuParams struct { + + /*ID + Id of sku to be obtained + + */ + ID string + /*Sku + updated sku containing all parameters except id + + */ + Sku *models.Sku + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the update sku params +func (o *UpdateSkuParams) WithTimeout(timeout time.Duration) *UpdateSkuParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the update sku params +func (o *UpdateSkuParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the update sku params +func (o *UpdateSkuParams) WithContext(ctx context.Context) *UpdateSkuParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the update sku params +func (o *UpdateSkuParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the update sku params +func (o *UpdateSkuParams) WithHTTPClient(client *http.Client) *UpdateSkuParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the update sku params +func (o *UpdateSkuParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the update sku params +func (o *UpdateSkuParams) WithID(id string) *UpdateSkuParams { + o.SetID(id) + return o +} + +// SetID adds the id to the update sku params +func (o *UpdateSkuParams) SetID(id string) { + o.ID = id +} + +// WithSku adds the sku to the update sku params +func (o *UpdateSkuParams) WithSku(sku *models.Sku) *UpdateSkuParams { + o.SetSku(sku) + return o +} + +// SetSku adds the sku to the update sku params +func (o *UpdateSkuParams) SetSku(sku *models.Sku) { + o.Sku = sku +} + +// WriteToRequest writes these params to a swagger request +func (o *UpdateSkuParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Sku != nil { + if err := r.SetBodyParam(o.Sku); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/sku_management/update_sku_responses.go b/services/plan-manager/client/sku_management/update_sku_responses.go new file mode 100644 index 0000000..55c6f55 --- /dev/null +++ b/services/plan-manager/client/sku_management/update_sku_responses.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateSkuReader is a Reader for the UpdateSku structure. +type UpdateSkuReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *UpdateSkuReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewUpdateSkuOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewUpdateSkuNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 500: + result := NewUpdateSkuInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewUpdateSkuOK creates a UpdateSkuOK with default headers values +func NewUpdateSkuOK() *UpdateSkuOK { + return &UpdateSkuOK{} +} + +/*UpdateSkuOK handles this case with default header values. + +updated sku +*/ +type UpdateSkuOK struct { + Payload *models.Sku +} + +func (o *UpdateSkuOK) Error() string { + return fmt.Sprintf("[PUT /sku/{id}][%d] updateSkuOK %+v", 200, o.Payload) +} + +func (o *UpdateSkuOK) GetPayload() *models.Sku { + return o.Payload +} + +func (o *UpdateSkuOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Sku) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateSkuNotFound creates a UpdateSkuNotFound with default headers values +func NewUpdateSkuNotFound() *UpdateSkuNotFound { + return &UpdateSkuNotFound{} +} + +/*UpdateSkuNotFound handles this case with default header values. + +sku with skuid not found +*/ +type UpdateSkuNotFound struct { + Payload *models.ErrorResponse +} + +func (o *UpdateSkuNotFound) Error() string { + return fmt.Sprintf("[PUT /sku/{id}][%d] updateSkuNotFound %+v", 404, o.Payload) +} + +func (o *UpdateSkuNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateSkuNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewUpdateSkuInternalServerError creates a UpdateSkuInternalServerError with default headers values +func NewUpdateSkuInternalServerError() *UpdateSkuInternalServerError { + return &UpdateSkuInternalServerError{} +} + +/*UpdateSkuInternalServerError handles this case with default header values. + +unexpected error +*/ +type UpdateSkuInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *UpdateSkuInternalServerError) Error() string { + return fmt.Sprintf("[PUT /sku/{id}][%d] updateSkuInternalServerError %+v", 500, o.Payload) +} + +func (o *UpdateSkuInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *UpdateSkuInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/status_management/get_status_parameters.go b/services/plan-manager/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..bc38256 --- /dev/null +++ b/services/plan-manager/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the endpoint to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/status_management/get_status_responses.go b/services/plan-manager/client/status_management/get_status_responses.go new file mode 100644 index 0000000..cdf9d72 --- /dev/null +++ b/services/plan-manager/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/status_management/show_status_parameters.go b/services/plan-manager/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/services/plan-manager/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/status_management/show_status_responses.go b/services/plan-manager/client/status_management/show_status_responses.go new file mode 100644 index 0000000..1f6bc97 --- /dev/null +++ b/services/plan-manager/client/status_management/show_status_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/status_management/status_management_client.go b/services/plan-manager/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/services/plan-manager/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/services/plan-manager/client/trigger_management/exec_sample_parameters.go b/services/plan-manager/client/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..2e1428d --- /dev/null +++ b/services/plan-manager/client/trigger_management/exec_sample_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// with the default values initialized. +func NewExecSampleParams() *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewExecSampleParamsWithTimeout creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewExecSampleParamsWithTimeout(timeout time.Duration) *ExecSampleParams { + + return &ExecSampleParams{ + + timeout: timeout, + } +} + +// NewExecSampleParamsWithContext creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a context for a request +func NewExecSampleParamsWithContext(ctx context.Context) *ExecSampleParams { + + return &ExecSampleParams{ + + Context: ctx, + } +} + +// NewExecSampleParamsWithHTTPClient creates a new ExecSampleParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewExecSampleParamsWithHTTPClient(client *http.Client) *ExecSampleParams { + + return &ExecSampleParams{ + HTTPClient: client, + } +} + +/*ExecSampleParams contains all the parameters to send to the API endpoint +for the exec sample operation typically these are written to a http.Request +*/ +type ExecSampleParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) WithTimeout(timeout time.Duration) *ExecSampleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the exec sample params +func (o *ExecSampleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the exec sample params +func (o *ExecSampleParams) WithContext(ctx context.Context) *ExecSampleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the exec sample params +func (o *ExecSampleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) WithHTTPClient(client *http.Client) *ExecSampleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the exec sample params +func (o *ExecSampleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ExecSampleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/client/trigger_management/exec_sample_responses.go b/services/plan-manager/client/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..9983f93 --- /dev/null +++ b/services/plan-manager/client/trigger_management/exec_sample_responses.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ExecSampleReader is a Reader for the ExecSample structure. +type ExecSampleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ExecSampleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewExecSampleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewExecSampleInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewExecSampleOK creates a ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + return &ExecSampleOK{} +} + +/*ExecSampleOK handles this case with default header values. + +Sample task executed successfully +*/ +type ExecSampleOK struct { +} + +func (o *ExecSampleOK) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleOK ", 200) +} + +func (o *ExecSampleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewExecSampleInternalServerError creates a ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + return &ExecSampleInternalServerError{} +} + +/*ExecSampleInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ExecSampleInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ExecSampleInternalServerError) Error() string { + return fmt.Sprintf("[GET /trigger/sample][%d] execSampleInternalServerError %+v", 500, o.Payload) +} + +func (o *ExecSampleInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ExecSampleInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/plan-manager/client/trigger_management/trigger_management_client.go b/services/plan-manager/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..b8010e0 --- /dev/null +++ b/services/plan-manager/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + ExecSample samples task trigger*/ + ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +ExecSample samples task trigger +*/ +func (a *Client) ExecSample(ctx context.Context, params *ExecSampleParams) (*ExecSampleOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "execSample", + Method: "GET", + PathPattern: "/trigger/sample", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ExecSampleReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ExecSampleOK), nil + +} diff --git a/services/plan-manager/go.mod b/services/plan-manager/go.mod new file mode 100644 index 0000000..a2f0a6c --- /dev/null +++ b/services/plan-manager/go.mod @@ -0,0 +1,35 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager + +go 1.15 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect + github.com/go-openapi/analysis v0.21.1 // indirect + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/go-resty/resty/v2 v2.7.0 // indirect + github.com/go-stack/stack v1.8.1 // indirect + github.com/jackc/pgx/v4 v4.14.1 // indirect + github.com/jinzhu/now v1.1.4 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/prometheus/client_golang v1.11.0 + github.com/prometheus/common v0.32.1 // indirect + github.com/prometheus/procfs v0.7.3 // indirect + github.com/rs/cors v1.8.2 + github.com/segmentio/ksuid v1.0.4 // indirect + github.com/spf13/viper v1.10.1 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + go.mongodb.org/mongo-driver v1.8.1 // indirect + golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 // indirect + golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect + golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/services/plan-manager/models/cycle.go b/services/plan-manager/models/cycle.go new file mode 100644 index 0000000..bb8037a --- /dev/null +++ b/services/plan-manager/models/cycle.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// Cycle cycle +// +// swagger:model Cycle +type Cycle struct { + + // ID + ID string `json:"ID,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // resource type + // Required: true + ResourceType *string `json:"ResourceType"` + + // sku list + // Required: true + SkuList datamodels.JSONdb `json:"SkuList" gorm:"type:jsonb"` + + // state + // Required: true + State *string `json:"State"` +} + +// Validate validates this cycle +func (m *Cycle) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateResourceType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSkuList(formats); err != nil { + res = append(res, err) + } + + if err := m.validateState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Cycle) validateResourceType(formats strfmt.Registry) error { + + if err := validate.Required("ResourceType", "body", m.ResourceType); err != nil { + return err + } + + return nil +} + +func (m *Cycle) validateSkuList(formats strfmt.Registry) error { + + if err := validate.Required("SkuList", "body", m.SkuList); err != nil { + return err + } + + return nil +} + +func (m *Cycle) validateState(formats strfmt.Registry) error { + + if err := validate.Required("State", "body", m.State); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Cycle) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Cycle) UnmarshalBinary(b []byte) error { + var res Cycle + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/models/error_response.go b/services/plan-manager/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/services/plan-manager/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/models/item_created_response.go b/services/plan-manager/models/item_created_response.go new file mode 100644 index 0000000..0d98e8c --- /dev/null +++ b/services/plan-manager/models/item_created_response.go @@ -0,0 +1,49 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ItemCreatedResponse item created response +// +// swagger:model ItemCreatedResponse +type ItemCreatedResponse struct { + + // ID + ID string `json:"ID,omitempty"` + + // link + Link string `json:"Link,omitempty"` + + // message + Message string `json:"Message,omitempty"` +} + +// Validate validates this item created response +func (m *ItemCreatedResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *ItemCreatedResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ItemCreatedResponse) UnmarshalBinary(b []byte) error { + var res ItemCreatedResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/models/plan.go b/services/plan-manager/models/plan.go new file mode 100644 index 0000000..d3661ec --- /dev/null +++ b/services/plan-manager/models/plan.go @@ -0,0 +1,148 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Plan plan +// +// swagger:model Plan +type Plan struct { + + // discount + Discount float64 `json:"Discount,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // ID + ID string `json:"ID,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // name + // Required: true + Name *string `json:"Name"` + + // offered end date + // Required: true + // Format: date + OfferedEndDate *strfmt.Date `json:"OfferedEndDate" gorm:"type:date"` + + // offered start date + // Required: true + // Format: date + OfferedStartDate *strfmt.Date `json:"OfferedStartDate" gorm:"type:date"` + + // sku prices + SkuPrices []*SkuPrice `json:"SkuPrices" gorm:"-"` +} + +// Validate validates this plan +func (m *Plan) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOfferedEndDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateOfferedStartDate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSkuPrices(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Plan) validateName(formats strfmt.Registry) error { + + if err := validate.Required("Name", "body", m.Name); err != nil { + return err + } + + return nil +} + +func (m *Plan) validateOfferedEndDate(formats strfmt.Registry) error { + + if err := validate.Required("OfferedEndDate", "body", m.OfferedEndDate); err != nil { + return err + } + + if err := validate.FormatOf("OfferedEndDate", "body", "date", m.OfferedEndDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Plan) validateOfferedStartDate(formats strfmt.Registry) error { + + if err := validate.Required("OfferedStartDate", "body", m.OfferedStartDate); err != nil { + return err + } + + if err := validate.FormatOf("OfferedStartDate", "body", "date", m.OfferedStartDate.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *Plan) validateSkuPrices(formats strfmt.Registry) error { + + if swag.IsZero(m.SkuPrices) { // not required + return nil + } + + for i := 0; i < len(m.SkuPrices); i++ { + if swag.IsZero(m.SkuPrices[i]) { // not required + continue + } + + if m.SkuPrices[i] != nil { + if err := m.SkuPrices[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("SkuPrices" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Plan) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Plan) UnmarshalBinary(b []byte) error { + var res Plan + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/models/sku.go b/services/plan-manager/models/sku.go new file mode 100644 index 0000000..da8507e --- /dev/null +++ b/services/plan-manager/models/sku.go @@ -0,0 +1,70 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Sku sku +// +// swagger:model Sku +type Sku struct { + + // ID + ID string `json:"ID,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // name + // Required: true + Name *string `json:"Name"` + + // unit + Unit string `json:"Unit,omitempty"` +} + +// Validate validates this sku +func (m *Sku) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Sku) validateName(formats strfmt.Registry) error { + + if err := validate.Required("Name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Sku) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Sku) UnmarshalBinary(b []byte) error { + var res Sku + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/models/sku_bundle.go b/services/plan-manager/models/sku_bundle.go new file mode 100644 index 0000000..d14b324 --- /dev/null +++ b/services/plan-manager/models/sku_bundle.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// SkuBundle sku bundle +// +// swagger:model SkuBundle +type SkuBundle struct { + + // ID + ID string `json:"ID,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // name + // Required: true + Name *string `json:"Name"` + + // sku prices + SkuPrices datamodels.JSONdb `json:"SkuPrices,omitempty" gorm:"type:jsonb"` +} + +// Validate validates this sku bundle +func (m *SkuBundle) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *SkuBundle) validateName(formats strfmt.Registry) error { + + if err := validate.Required("Name", "body", m.Name); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SkuBundle) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SkuBundle) UnmarshalBinary(b []byte) error { + var res SkuBundle + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/models/sku_price.go b/services/plan-manager/models/sku_price.go new file mode 100644 index 0000000..15592f0 --- /dev/null +++ b/services/plan-manager/models/sku_price.go @@ -0,0 +1,186 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// SkuPrice sku price +// +// swagger:model SkuPrice +type SkuPrice struct { + + // accounting mode + // Enum: [CREDIT CASH BOTH NONE] + AccountingMode *string `json:"AccountingMode,omitempty" gorm:"index;default:CREDIT"` + + // discount + Discount float64 `json:"Discount,omitempty" gorm:"type:numeric(23,13);default:0.0"` + + // ID + ID string `json:"ID,omitempty" gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid"` + + // plan ID + // Required: true + PlanID *string `json:"PlanID"` + + // sku ID + // Required: true + SkuID *string `json:"SkuID"` + + // sku name + SkuName string `json:"SkuName,omitempty"` + + // unit + // Required: true + Unit *string `json:"Unit"` + + // unit credit price + UnitCreditPrice float64 `json:"UnitCreditPrice,omitempty" gorm:"type:numeric(23,13)"` + + // unit price + // Required: true + UnitPrice *float64 `json:"UnitPrice" gorm:"type:numeric(23,13)"` +} + +// Validate validates this sku price +func (m *SkuPrice) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAccountingMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePlanID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSkuID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUnit(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUnitPrice(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var skuPriceTypeAccountingModePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["CREDIT","CASH","BOTH","NONE"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + skuPriceTypeAccountingModePropEnum = append(skuPriceTypeAccountingModePropEnum, v) + } +} + +const ( + + // SkuPriceAccountingModeCREDIT captures enum value "CREDIT" + SkuPriceAccountingModeCREDIT string = "CREDIT" + + // SkuPriceAccountingModeCASH captures enum value "CASH" + SkuPriceAccountingModeCASH string = "CASH" + + // SkuPriceAccountingModeBOTH captures enum value "BOTH" + SkuPriceAccountingModeBOTH string = "BOTH" + + // SkuPriceAccountingModeNONE captures enum value "NONE" + SkuPriceAccountingModeNONE string = "NONE" +) + +// prop value enum +func (m *SkuPrice) validateAccountingModeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, skuPriceTypeAccountingModePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *SkuPrice) validateAccountingMode(formats strfmt.Registry) error { + + if swag.IsZero(m.AccountingMode) { // not required + return nil + } + + // value enum + if err := m.validateAccountingModeEnum("AccountingMode", "body", *m.AccountingMode); err != nil { + return err + } + + return nil +} + +func (m *SkuPrice) validatePlanID(formats strfmt.Registry) error { + + if err := validate.Required("PlanID", "body", m.PlanID); err != nil { + return err + } + + return nil +} + +func (m *SkuPrice) validateSkuID(formats strfmt.Registry) error { + + if err := validate.Required("SkuID", "body", m.SkuID); err != nil { + return err + } + + return nil +} + +func (m *SkuPrice) validateUnit(formats strfmt.Registry) error { + + if err := validate.Required("Unit", "body", m.Unit); err != nil { + return err + } + + return nil +} + +func (m *SkuPrice) validateUnitPrice(formats strfmt.Registry) error { + + if err := validate.Required("UnitPrice", "body", m.UnitPrice); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *SkuPrice) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SkuPrice) UnmarshalBinary(b []byte) error { + var res SkuPrice + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/models/status.go b/services/plan-manager/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/services/plan-manager/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/plan-manager/restapi/configure_plan_manager_management_api.go b/services/plan-manager/restapi/configure_plan_manager_management_api.go new file mode 100644 index 0000000..c483d88 --- /dev/null +++ b/services/plan-manager/restapi/configure_plan_manager_management_api.go @@ -0,0 +1,384 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/bundle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/cycle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/plan_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/price_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/sku_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/trigger_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name BundleManagementAPI -inpkg + +/* BundleManagementAPI */ +type BundleManagementAPI interface { + /* CreateSkuBundle create SKU bundle */ + CreateSkuBundle(ctx context.Context, params bundle_management.CreateSkuBundleParams) middleware.Responder + + /* GetSkuBundle Get specific sku bundle */ + GetSkuBundle(ctx context.Context, params bundle_management.GetSkuBundleParams) middleware.Responder + + /* GetSkuBundleByName Get specific sku bundle */ + GetSkuBundleByName(ctx context.Context, params bundle_management.GetSkuBundleByNameParams) middleware.Responder + + /* ListSkuBundles list SKU Bundles */ + ListSkuBundles(ctx context.Context, params bundle_management.ListSkuBundlesParams) middleware.Responder + + /* UpdateSkuBundle Update specific sku bundle */ + UpdateSkuBundle(ctx context.Context, params bundle_management.UpdateSkuBundleParams) middleware.Responder +} + +//go:generate mockery -name CycleManagementAPI -inpkg + +/* CycleManagementAPI */ +type CycleManagementAPI interface { + /* CreateCycle Create a plan */ + CreateCycle(ctx context.Context, params cycle_management.CreateCycleParams) middleware.Responder + + /* GetCycle Get specific cycle */ + GetCycle(ctx context.Context, params cycle_management.GetCycleParams) middleware.Responder + + /* ListCycles List all cycles */ + ListCycles(ctx context.Context, params cycle_management.ListCyclesParams) middleware.Responder + + /* UpdateCycle Update specific cycle */ + UpdateCycle(ctx context.Context, params cycle_management.UpdateCycleParams) middleware.Responder +} + +//go:generate mockery -name PlanManagementAPI -inpkg + +/* PlanManagementAPI */ +type PlanManagementAPI interface { + /* CreatePlan Create a plan */ + CreatePlan(ctx context.Context, params plan_management.CreatePlanParams) middleware.Responder + + /* GetCompletePlan Get complete plan */ + GetCompletePlan(ctx context.Context, params plan_management.GetCompletePlanParams) middleware.Responder + + /* GetPlan Get specific plan */ + GetPlan(ctx context.Context, params plan_management.GetPlanParams) middleware.Responder + + /* ListCompletePlans Get full information relating to known plans */ + ListCompletePlans(ctx context.Context, params plan_management.ListCompletePlansParams) middleware.Responder + + /* ListPlans List all plans */ + ListPlans(ctx context.Context, params plan_management.ListPlansParams) middleware.Responder + + /* UpdatePlan Update specific plan */ + UpdatePlan(ctx context.Context, params plan_management.UpdatePlanParams) middleware.Responder +} + +//go:generate mockery -name PriceManagementAPI -inpkg + +/* PriceManagementAPI */ +type PriceManagementAPI interface { + /* CreateSkuPrice create SKU price */ + CreateSkuPrice(ctx context.Context, params price_management.CreateSkuPriceParams) middleware.Responder + + /* GetSkuPrice Get specific sku price */ + GetSkuPrice(ctx context.Context, params price_management.GetSkuPriceParams) middleware.Responder + + /* ListSkuPrices list SKU Prices */ + ListSkuPrices(ctx context.Context, params price_management.ListSkuPricesParams) middleware.Responder + + /* UpdateSkuPrice Update specific sku price */ + UpdateSkuPrice(ctx context.Context, params price_management.UpdateSkuPriceParams) middleware.Responder +} + +//go:generate mockery -name SkuManagementAPI -inpkg + +/* SkuManagementAPI */ +type SkuManagementAPI interface { + /* CreateSku create SKU */ + CreateSku(ctx context.Context, params sku_management.CreateSkuParams) middleware.Responder + + /* GetSku Get specific sku */ + GetSku(ctx context.Context, params sku_management.GetSkuParams) middleware.Responder + + /* ListSkus list SKUs */ + ListSkus(ctx context.Context, params sku_management.ListSkusParams) middleware.Responder + + /* UpdateSku Update specific sku */ + UpdateSku(ctx context.Context, params sku_management.UpdateSkuParams) middleware.Responder +} + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* ExecSample Sample task trigger */ + ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + BundleManagementAPI + CycleManagementAPI + PlanManagementAPI + PriceManagementAPI + SkuManagementAPI + StatusManagementAPI + TriggerManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) + // Authenticator to use for all APIKey authentication + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // Authenticator to use for all Bearer authentication + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // Authenticator to use for all Basic authentication + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *PlanManagerManagementAPI instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.PlanManagerManagementAPIAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewPlanManagerManagementAPIAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + if c.APIKeyAuthenticator != nil { + api.APIKeyAuthenticator = c.APIKeyAuthenticator + } + if c.BasicAuthenticator != nil { + api.BasicAuthenticator = c.BasicAuthenticator + } + if c.BearerAuthenticator != nil { + api.BearerAuthenticator = c.BearerAuthenticator + } + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.CycleManagementCreateCycleHandler = cycle_management.CreateCycleHandlerFunc(func(params cycle_management.CreateCycleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CycleManagementAPI.CreateCycle(ctx, params) + }) + api.PlanManagementCreatePlanHandler = plan_management.CreatePlanHandlerFunc(func(params plan_management.CreatePlanParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PlanManagementAPI.CreatePlan(ctx, params) + }) + api.SkuManagementCreateSkuHandler = sku_management.CreateSkuHandlerFunc(func(params sku_management.CreateSkuParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.SkuManagementAPI.CreateSku(ctx, params) + }) + api.BundleManagementCreateSkuBundleHandler = bundle_management.CreateSkuBundleHandlerFunc(func(params bundle_management.CreateSkuBundleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BundleManagementAPI.CreateSkuBundle(ctx, params) + }) + api.PriceManagementCreateSkuPriceHandler = price_management.CreateSkuPriceHandlerFunc(func(params price_management.CreateSkuPriceParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PriceManagementAPI.CreateSkuPrice(ctx, params) + }) + api.TriggerManagementExecSampleHandler = trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.ExecSample(ctx, params) + }) + api.PlanManagementGetCompletePlanHandler = plan_management.GetCompletePlanHandlerFunc(func(params plan_management.GetCompletePlanParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PlanManagementAPI.GetCompletePlan(ctx, params) + }) + api.CycleManagementGetCycleHandler = cycle_management.GetCycleHandlerFunc(func(params cycle_management.GetCycleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CycleManagementAPI.GetCycle(ctx, params) + }) + api.PlanManagementGetPlanHandler = plan_management.GetPlanHandlerFunc(func(params plan_management.GetPlanParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PlanManagementAPI.GetPlan(ctx, params) + }) + api.SkuManagementGetSkuHandler = sku_management.GetSkuHandlerFunc(func(params sku_management.GetSkuParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.SkuManagementAPI.GetSku(ctx, params) + }) + api.BundleManagementGetSkuBundleHandler = bundle_management.GetSkuBundleHandlerFunc(func(params bundle_management.GetSkuBundleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BundleManagementAPI.GetSkuBundle(ctx, params) + }) + api.BundleManagementGetSkuBundleByNameHandler = bundle_management.GetSkuBundleByNameHandlerFunc(func(params bundle_management.GetSkuBundleByNameParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BundleManagementAPI.GetSkuBundleByName(ctx, params) + }) + api.PriceManagementGetSkuPriceHandler = price_management.GetSkuPriceHandlerFunc(func(params price_management.GetSkuPriceParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PriceManagementAPI.GetSkuPrice(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.PlanManagementListCompletePlansHandler = plan_management.ListCompletePlansHandlerFunc(func(params plan_management.ListCompletePlansParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PlanManagementAPI.ListCompletePlans(ctx, params) + }) + api.CycleManagementListCyclesHandler = cycle_management.ListCyclesHandlerFunc(func(params cycle_management.ListCyclesParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CycleManagementAPI.ListCycles(ctx, params) + }) + api.PlanManagementListPlansHandler = plan_management.ListPlansHandlerFunc(func(params plan_management.ListPlansParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PlanManagementAPI.ListPlans(ctx, params) + }) + api.BundleManagementListSkuBundlesHandler = bundle_management.ListSkuBundlesHandlerFunc(func(params bundle_management.ListSkuBundlesParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BundleManagementAPI.ListSkuBundles(ctx, params) + }) + api.PriceManagementListSkuPricesHandler = price_management.ListSkuPricesHandlerFunc(func(params price_management.ListSkuPricesParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PriceManagementAPI.ListSkuPrices(ctx, params) + }) + api.SkuManagementListSkusHandler = sku_management.ListSkusHandlerFunc(func(params sku_management.ListSkusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.SkuManagementAPI.ListSkus(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.CycleManagementUpdateCycleHandler = cycle_management.UpdateCycleHandlerFunc(func(params cycle_management.UpdateCycleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.CycleManagementAPI.UpdateCycle(ctx, params) + }) + api.PlanManagementUpdatePlanHandler = plan_management.UpdatePlanHandlerFunc(func(params plan_management.UpdatePlanParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PlanManagementAPI.UpdatePlan(ctx, params) + }) + api.SkuManagementUpdateSkuHandler = sku_management.UpdateSkuHandlerFunc(func(params sku_management.UpdateSkuParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.SkuManagementAPI.UpdateSku(ctx, params) + }) + api.BundleManagementUpdateSkuBundleHandler = bundle_management.UpdateSkuBundleHandlerFunc(func(params bundle_management.UpdateSkuBundleParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.BundleManagementAPI.UpdateSkuBundle(ctx, params) + }) + api.PriceManagementUpdateSkuPriceHandler = price_management.UpdateSkuPriceHandlerFunc(func(params price_management.UpdateSkuPriceParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.PriceManagementAPI.UpdateSkuPrice(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/services/plan-manager/restapi/doc.go b/services/plan-manager/restapi/doc.go new file mode 100644 index 0000000..7dc7ebf --- /dev/null +++ b/services/plan-manager/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi Plan Manager Management API +// +// An API which supports creation, deletion, listing etc of Plan Manager +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v1.0 +// Version: 1.0.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/services/plan-manager/restapi/embedded_spec.go b/services/plan-manager/restapi/embedded_spec.go new file mode 100644 index 0000000..45eea5c --- /dev/null +++ b/services/plan-manager/restapi/embedded_spec.go @@ -0,0 +1,2886 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Plan Manager", + "title": "Plan Manager Management API", + "contact": { + "email": "sean@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/cycle": { + "get": { + "description": "lists all cycles", + "tags": [ + "cycleManagement" + ], + "summary": "List all cycles", + "operationId": "listCycles", + "parameters": [ + { + "type": "string", + "description": "state to filter", + "name": "state", + "in": "query" + }, + { + "type": "string", + "description": "resource type to filter", + "name": "type", + "in": "query" + } + ], + "responses": { + "200": { + "description": "list of cycles returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Cycle" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new cycle", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cycleManagement" + ], + "summary": "Create a plan", + "operationId": "createCycle", + "parameters": [ + { + "description": "Cycle to be added", + "name": "cycle", + "in": "body", + "schema": { + "$ref": "#/definitions/Cycle" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/cycle/{id}": { + "get": { + "description": "get cycle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cycleManagement" + ], + "summary": "Get specific cycle", + "operationId": "getCycle", + "parameters": [ + { + "type": "string", + "description": "Id of cycle to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "cycle returned", + "schema": { + "$ref": "#/definitions/Cycle" + } + }, + "404": { + "description": "cycle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update cycle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cycleManagement" + ], + "summary": "Update specific cycle", + "operationId": "updateCycle", + "parameters": [ + { + "type": "string", + "description": "Id of cycle to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated cycle containing all parameters except id", + "name": "cycle", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Cycle" + } + } + ], + "responses": { + "200": { + "description": "updated cycle", + "schema": { + "$ref": "#/definitions/Cycle" + } + }, + "404": { + "description": "cycle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan": { + "get": { + "description": "lists all plans (tbd - pagination?)", + "tags": [ + "planManagement" + ], + "summary": "List all plans", + "operationId": "listPlans", + "responses": { + "200": { + "description": "list of plans returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Plan" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new plan", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Create a plan", + "operationId": "createPlan", + "parameters": [ + { + "description": "Plan to be added", + "name": "plan", + "in": "body", + "schema": { + "$ref": "#/definitions/Plan" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan/complete": { + "get": { + "description": "Obtains full information on all known plans", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Get full information relating to known plans", + "operationId": "listCompletePlans", + "responses": { + "200": { + "description": "Set of known plans returned in full", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Plan" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan/complete/{id}": { + "get": { + "description": "gets complete plan with planid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Get complete plan", + "operationId": "getCompletePlan", + "parameters": [ + { + "type": "string", + "description": "Id of plan to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "plan returned", + "schema": { + "$ref": "#/definitions/Plan" + } + }, + "404": { + "description": "complete plan with planid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan/{id}": { + "get": { + "description": "get plan with given planid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Get specific plan", + "operationId": "getPlan", + "parameters": [ + { + "type": "string", + "description": "Id of plan to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "plan returned", + "schema": { + "$ref": "#/definitions/Plan" + } + }, + "404": { + "description": "plan with planid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update plan with given planId", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Update specific plan", + "operationId": "updatePlan", + "parameters": [ + { + "type": "string", + "description": "Id of plan to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated plan containing all parameters except id", + "name": "plan", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Plan" + } + } + ], + "responses": { + "200": { + "description": "updated plan", + "schema": { + "$ref": "#/definitions/Plan" + } + }, + "404": { + "description": "plan with planid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku": { + "get": { + "description": "lists all skus", + "tags": [ + "skuManagement" + ], + "summary": "list SKUs", + "operationId": "listSkus", + "responses": { + "200": { + "description": "list of skus returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Sku" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new sku", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "skuManagement" + ], + "summary": "create SKU", + "operationId": "createSku", + "parameters": [ + { + "description": "SKU to be added", + "name": "sku", + "in": "body", + "schema": { + "$ref": "#/definitions/Sku" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/bundle": { + "get": { + "description": "lists all sku bundles", + "tags": [ + "bundleManagement" + ], + "summary": "list SKU Bundles", + "operationId": "listSkuBundles", + "responses": { + "200": { + "description": "list of skus bundles returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/SkuBundle" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new sku bundle", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "create SKU bundle", + "operationId": "createSkuBundle", + "parameters": [ + { + "description": "SKU bundle to be added", + "name": "bundle", + "in": "body", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/bundle/name/{name}": { + "get": { + "description": "get sku bundle with given name", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "Get specific sku bundle", + "operationId": "getSkuBundleByName", + "parameters": [ + { + "type": "string", + "description": "Id of sku bundle to be obtained", + "name": "name", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku bundle returned", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + }, + "404": { + "description": "sku bundle with name not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/bundle/{id}": { + "get": { + "description": "get sku bundle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "Get specific sku bundle", + "operationId": "getSkuBundle", + "parameters": [ + { + "type": "string", + "description": "Id of sku bundle to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku bundle returned", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + }, + "404": { + "description": "sku bundle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update sku bundle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "Update specific sku bundle", + "operationId": "updateSkuBundle", + "parameters": [ + { + "type": "string", + "description": "Id of sku bundle to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated sku bundle containing all parameters except id", + "name": "bundle", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/SkuBundle" + } + } + ], + "responses": { + "200": { + "description": "updated sku bundle", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + }, + "404": { + "description": "sku bundle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/price": { + "get": { + "description": "lists all sku prices", + "tags": [ + "priceManagement" + ], + "summary": "list SKU Prices", + "operationId": "listSkuPrices", + "responses": { + "200": { + "description": "list of skus prices returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/SkuPrice" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new sku price", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "priceManagement" + ], + "summary": "create SKU price", + "operationId": "createSkuPrice", + "parameters": [ + { + "description": "SKU price to be added", + "name": "price", + "in": "body", + "schema": { + "$ref": "#/definitions/SkuPrice" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/price/{id}": { + "get": { + "description": "get sku price with given skupriceid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "priceManagement" + ], + "summary": "Get specific sku price", + "operationId": "getSkuPrice", + "parameters": [ + { + "type": "string", + "description": "Id of sku price to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku price returned", + "schema": { + "$ref": "#/definitions/SkuPrice" + } + }, + "404": { + "description": "sku price with skupriceid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update sku price with given skupriceid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "priceManagement" + ], + "summary": "Update specific sku price", + "operationId": "updateSkuPrice", + "parameters": [ + { + "type": "string", + "description": "Id of sku price to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated sku containing all parameters except id", + "name": "price", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/SkuPrice" + } + } + ], + "responses": { + "200": { + "description": "updated sku price", + "schema": { + "$ref": "#/definitions/SkuPrice" + } + }, + "404": { + "description": "sku price with skupriceid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/{id}": { + "get": { + "description": "get sku with given skuid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "skuManagement" + ], + "summary": "Get specific sku", + "operationId": "getSku", + "parameters": [ + { + "type": "string", + "description": "Id of sku to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku returned", + "schema": { + "$ref": "#/definitions/Sku" + } + }, + "404": { + "description": "sku with skuid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update sku with given skuid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "skuManagement" + ], + "summary": "Update specific sku", + "operationId": "updateSku", + "parameters": [ + { + "type": "string", + "description": "Id of sku to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated sku containing all parameters except id", + "name": "sku", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Sku" + } + } + ], + "responses": { + "200": { + "description": "updated sku", + "schema": { + "$ref": "#/definitions/Sku" + } + }, + "404": { + "description": "sku with skuid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "bundle", + "cycle", + "plan", + "price", + "sku" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "Cycle": { + "type": "object", + "required": [ + "State", + "ResourceType", + "SkuList" + ], + "properties": { + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "ResourceType": { + "type": "string" + }, + "SkuList": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "State": { + "type": "string" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ID": { + "type": "string" + }, + "Link": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Plan": { + "type": "object", + "required": [ + "Name", + "OfferedEndDate", + "OfferedStartDate" + ], + "properties": { + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Name": { + "type": "string", + "example": "Standard 3 year plan starting 1/1/2019" + }, + "OfferedEndDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"", + "example": "2016-08-29" + }, + "OfferedStartDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"", + "example": "2016-08-29" + }, + "SkuPrices": { + "type": "array", + "items": { + "$ref": "#/definitions/SkuPrice" + }, + "x-go-custom-tag": "gorm:\"-\"" + } + } + }, + "Sku": { + "type": "object", + "required": [ + "Name" + ], + "properties": { + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Name": { + "type": "string", + "example": "Standard 3 year plan starting 1/1/2019" + }, + "Unit": { + "type": "string" + } + } + }, + "SkuBundle": { + "type": "object", + "required": [ + "Name" + ], + "properties": { + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Name": { + "type": "string" + }, + "SkuPrices": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "SkuPrice": { + "type": "object", + "required": [ + "PlanID", + "SkuID", + "Unit", + "UnitPrice" + ], + "properties": { + "AccountingMode": { + "type": "string", + "default": "CREDIT", + "enum": [ + "CREDIT", + "CASH", + "BOTH", + "NONE" + ], + "x-go-custom-tag": "gorm:\"index;default:CREDIT\"" + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "PlanID": { + "type": "string" + }, + "SkuID": { + "type": "string" + }, + "SkuName": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UnitCreditPrice": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + }, + "UnitPrice": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to management of sku bundles", + "name": "bundleManagement" + }, + { + "description": "Actions relating to management of life cycles", + "name": "cycleManagement" + }, + { + "description": "Actions relating to management of plans", + "name": "planManagement" + }, + { + "description": "Actions relating to management of sku prices", + "name": "priceManagement" + }, + { + "description": "Actions relating to management of skus and prices", + "name": "skuManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of Plan Manager", + "title": "Plan Manager Management API", + "contact": { + "email": "sean@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/cycle": { + "get": { + "description": "lists all cycles", + "tags": [ + "cycleManagement" + ], + "summary": "List all cycles", + "operationId": "listCycles", + "parameters": [ + { + "type": "string", + "description": "state to filter", + "name": "state", + "in": "query" + }, + { + "type": "string", + "description": "resource type to filter", + "name": "type", + "in": "query" + } + ], + "responses": { + "200": { + "description": "list of cycles returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Cycle" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new cycle", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cycleManagement" + ], + "summary": "Create a plan", + "operationId": "createCycle", + "parameters": [ + { + "description": "Cycle to be added", + "name": "cycle", + "in": "body", + "schema": { + "$ref": "#/definitions/Cycle" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/cycle/{id}": { + "get": { + "description": "get cycle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cycleManagement" + ], + "summary": "Get specific cycle", + "operationId": "getCycle", + "parameters": [ + { + "type": "string", + "description": "Id of cycle to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "cycle returned", + "schema": { + "$ref": "#/definitions/Cycle" + } + }, + "404": { + "description": "cycle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update cycle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "cycleManagement" + ], + "summary": "Update specific cycle", + "operationId": "updateCycle", + "parameters": [ + { + "type": "string", + "description": "Id of cycle to be updated", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated cycle containing all parameters except id", + "name": "cycle", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Cycle" + } + } + ], + "responses": { + "200": { + "description": "updated cycle", + "schema": { + "$ref": "#/definitions/Cycle" + } + }, + "404": { + "description": "cycle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan": { + "get": { + "description": "lists all plans (tbd - pagination?)", + "tags": [ + "planManagement" + ], + "summary": "List all plans", + "operationId": "listPlans", + "responses": { + "200": { + "description": "list of plans returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Plan" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new plan", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Create a plan", + "operationId": "createPlan", + "parameters": [ + { + "description": "Plan to be added", + "name": "plan", + "in": "body", + "schema": { + "$ref": "#/definitions/Plan" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan/complete": { + "get": { + "description": "Obtains full information on all known plans", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Get full information relating to known plans", + "operationId": "listCompletePlans", + "responses": { + "200": { + "description": "Set of known plans returned in full", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Plan" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan/complete/{id}": { + "get": { + "description": "gets complete plan with planid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Get complete plan", + "operationId": "getCompletePlan", + "parameters": [ + { + "type": "string", + "description": "Id of plan to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "plan returned", + "schema": { + "$ref": "#/definitions/Plan" + } + }, + "404": { + "description": "complete plan with planid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/plan/{id}": { + "get": { + "description": "get plan with given planid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Get specific plan", + "operationId": "getPlan", + "parameters": [ + { + "type": "string", + "description": "Id of plan to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "plan returned", + "schema": { + "$ref": "#/definitions/Plan" + } + }, + "404": { + "description": "plan with planid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update plan with given planId", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "planManagement" + ], + "summary": "Update specific plan", + "operationId": "updatePlan", + "parameters": [ + { + "type": "string", + "description": "Id of plan to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated plan containing all parameters except id", + "name": "plan", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Plan" + } + } + ], + "responses": { + "200": { + "description": "updated plan", + "schema": { + "$ref": "#/definitions/Plan" + } + }, + "404": { + "description": "plan with planid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku": { + "get": { + "description": "lists all skus", + "tags": [ + "skuManagement" + ], + "summary": "list SKUs", + "operationId": "listSkus", + "responses": { + "200": { + "description": "list of skus returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Sku" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new sku", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "skuManagement" + ], + "summary": "create SKU", + "operationId": "createSku", + "parameters": [ + { + "description": "SKU to be added", + "name": "sku", + "in": "body", + "schema": { + "$ref": "#/definitions/Sku" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/bundle": { + "get": { + "description": "lists all sku bundles", + "tags": [ + "bundleManagement" + ], + "summary": "list SKU Bundles", + "operationId": "listSkuBundles", + "responses": { + "200": { + "description": "list of skus bundles returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/SkuBundle" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new sku bundle", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "create SKU bundle", + "operationId": "createSkuBundle", + "parameters": [ + { + "description": "SKU bundle to be added", + "name": "bundle", + "in": "body", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/bundle/name/{name}": { + "get": { + "description": "get sku bundle with given name", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "Get specific sku bundle", + "operationId": "getSkuBundleByName", + "parameters": [ + { + "type": "string", + "description": "Id of sku bundle to be obtained", + "name": "name", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku bundle returned", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + }, + "404": { + "description": "sku bundle with name not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/bundle/{id}": { + "get": { + "description": "get sku bundle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "Get specific sku bundle", + "operationId": "getSkuBundle", + "parameters": [ + { + "type": "string", + "description": "Id of sku bundle to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku bundle returned", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + }, + "404": { + "description": "sku bundle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update sku bundle with given id", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "bundleManagement" + ], + "summary": "Update specific sku bundle", + "operationId": "updateSkuBundle", + "parameters": [ + { + "type": "string", + "description": "Id of sku bundle to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated sku bundle containing all parameters except id", + "name": "bundle", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/SkuBundle" + } + } + ], + "responses": { + "200": { + "description": "updated sku bundle", + "schema": { + "$ref": "#/definitions/SkuBundle" + } + }, + "404": { + "description": "sku bundle with id not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/price": { + "get": { + "description": "lists all sku prices", + "tags": [ + "priceManagement" + ], + "summary": "list SKU Prices", + "operationId": "listSkuPrices", + "responses": { + "200": { + "description": "list of skus prices returned", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/SkuPrice" + } + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "post": { + "description": "Creates a new sku price", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "priceManagement" + ], + "summary": "create SKU price", + "operationId": "createSkuPrice", + "parameters": [ + { + "description": "SKU price to be added", + "name": "price", + "in": "body", + "schema": { + "$ref": "#/definitions/SkuPrice" + } + } + ], + "responses": { + "201": { + "description": "item created", + "schema": { + "$ref": "#/definitions/ItemCreatedResponse" + } + }, + "400": { + "description": "invalid input, object invalid" + }, + "409": { + "description": "an existing item already exists", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/price/{id}": { + "get": { + "description": "get sku price with given skupriceid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "priceManagement" + ], + "summary": "Get specific sku price", + "operationId": "getSkuPrice", + "parameters": [ + { + "type": "string", + "description": "Id of sku price to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku price returned", + "schema": { + "$ref": "#/definitions/SkuPrice" + } + }, + "404": { + "description": "sku price with skupriceid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update sku price with given skupriceid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "priceManagement" + ], + "summary": "Update specific sku price", + "operationId": "updateSkuPrice", + "parameters": [ + { + "type": "string", + "description": "Id of sku price to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated sku containing all parameters except id", + "name": "price", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/SkuPrice" + } + } + ], + "responses": { + "200": { + "description": "updated sku price", + "schema": { + "$ref": "#/definitions/SkuPrice" + } + }, + "404": { + "description": "sku price with skupriceid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/sku/{id}": { + "get": { + "description": "get sku with given skuid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "skuManagement" + ], + "summary": "Get specific sku", + "operationId": "getSku", + "parameters": [ + { + "type": "string", + "description": "Id of sku to be obtained", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "sku returned", + "schema": { + "$ref": "#/definitions/Sku" + } + }, + "404": { + "description": "sku with skuid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + }, + "put": { + "description": "Update sku with given skuid", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "skuManagement" + ], + "summary": "Update specific sku", + "operationId": "updateSku", + "parameters": [ + { + "type": "string", + "description": "Id of sku to be obtained", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "updated sku containing all parameters except id", + "name": "sku", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Sku" + } + } + ], + "responses": { + "200": { + "description": "updated sku", + "schema": { + "$ref": "#/definitions/Sku" + } + }, + "404": { + "description": "sku with skuid not found", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + }, + "500": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "bundle", + "cycle", + "plan", + "price", + "sku" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/sample": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Sample task trigger", + "operationId": "execSample", + "responses": { + "200": { + "description": "Sample task executed successfully" + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "Cycle": { + "type": "object", + "required": [ + "State", + "ResourceType", + "SkuList" + ], + "properties": { + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "ResourceType": { + "type": "string" + }, + "SkuList": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "State": { + "type": "string" + } + } + }, + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "ItemCreatedResponse": { + "properties": { + "ID": { + "type": "string" + }, + "Link": { + "type": "string" + }, + "Message": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Plan": { + "type": "object", + "required": [ + "Name", + "OfferedEndDate", + "OfferedStartDate" + ], + "properties": { + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Name": { + "type": "string", + "example": "Standard 3 year plan starting 1/1/2019" + }, + "OfferedEndDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"", + "example": "2016-08-29" + }, + "OfferedStartDate": { + "type": "string", + "format": "date", + "x-go-custom-tag": "gorm:\"type:date\"", + "example": "2016-08-29" + }, + "SkuPrices": { + "type": "array", + "items": { + "$ref": "#/definitions/SkuPrice" + }, + "x-go-custom-tag": "gorm:\"-\"" + } + } + }, + "Sku": { + "type": "object", + "required": [ + "Name" + ], + "properties": { + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Name": { + "type": "string", + "example": "Standard 3 year plan starting 1/1/2019" + }, + "Unit": { + "type": "string" + } + } + }, + "SkuBundle": { + "type": "object", + "required": [ + "Name" + ], + "properties": { + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "Name": { + "type": "string" + }, + "SkuPrices": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "SkuPrice": { + "type": "object", + "required": [ + "PlanID", + "SkuID", + "Unit", + "UnitPrice" + ], + "properties": { + "AccountingMode": { + "type": "string", + "default": "CREDIT", + "enum": [ + "CREDIT", + "CASH", + "BOTH", + "NONE" + ], + "x-go-custom-tag": "gorm:\"index;default:CREDIT\"" + }, + "Discount": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + }, + "ID": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid\"" + }, + "PlanID": { + "type": "string" + }, + "SkuID": { + "type": "string" + }, + "SkuName": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UnitCreditPrice": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + }, + "UnitPrice": { + "type": "number", + "format": "double", + "x-go-custom-tag": "gorm:\"type:numeric(23,13)\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "admin", + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to management of sku bundles", + "name": "bundleManagement" + }, + { + "description": "Actions relating to management of life cycles", + "name": "cycleManagement" + }, + { + "description": "Actions relating to management of plans", + "name": "planManagement" + }, + { + "description": "Actions relating to management of sku prices", + "name": "priceManagement" + }, + { + "description": "Actions relating to management of skus and prices", + "name": "skuManagement" + } + ] +}`)) +} diff --git a/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle.go b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle.go new file mode 100644 index 0000000..abf3d56 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// CreateSkuBundleHandlerFunc turns a function with the right signature into a create sku bundle handler +type CreateSkuBundleHandlerFunc func(CreateSkuBundleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn CreateSkuBundleHandlerFunc) Handle(params CreateSkuBundleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// CreateSkuBundleHandler interface for that can handle valid create sku bundle params +type CreateSkuBundleHandler interface { + Handle(CreateSkuBundleParams, interface{}) middleware.Responder +} + +// NewCreateSkuBundle creates a new http.Handler for the create sku bundle operation +func NewCreateSkuBundle(ctx *middleware.Context, handler CreateSkuBundleHandler) *CreateSkuBundle { + return &CreateSkuBundle{Context: ctx, Handler: handler} +} + +/*CreateSkuBundle swagger:route POST /sku/bundle bundleManagement createSkuBundle + +create SKU bundle + +Creates a new sku bundle + +*/ +type CreateSkuBundle struct { + Context *middleware.Context + Handler CreateSkuBundleHandler +} + +func (o *CreateSkuBundle) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewCreateSkuBundleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_parameters.go b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_parameters.go new file mode 100644 index 0000000..8a387dd --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_parameters.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateSkuBundleParams creates a new CreateSkuBundleParams object +// no default values defined in spec. +func NewCreateSkuBundleParams() CreateSkuBundleParams { + + return CreateSkuBundleParams{} +} + +// CreateSkuBundleParams contains all the bound params for the create sku bundle operation +// typically these are obtained from a http.Request +// +// swagger:parameters createSkuBundle +type CreateSkuBundleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*SKU bundle to be added + In: body + */ + Bundle *models.SkuBundle +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewCreateSkuBundleParams() beforehand. +func (o *CreateSkuBundleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.SkuBundle + if err := route.Consumer.Consume(r.Body, &body); err != nil { + res = append(res, errors.NewParseError("bundle", "body", "", err)) + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Bundle = &body + } + } + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_responses.go b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_responses.go new file mode 100644 index 0000000..41eb6b1 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_responses.go @@ -0,0 +1,170 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateSkuBundleCreatedCode is the HTTP code returned for type CreateSkuBundleCreated +const CreateSkuBundleCreatedCode int = 201 + +/*CreateSkuBundleCreated item created + +swagger:response createSkuBundleCreated +*/ +type CreateSkuBundleCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewCreateSkuBundleCreated creates CreateSkuBundleCreated with default headers values +func NewCreateSkuBundleCreated() *CreateSkuBundleCreated { + + return &CreateSkuBundleCreated{} +} + +// WithPayload adds the payload to the create sku bundle created response +func (o *CreateSkuBundleCreated) WithPayload(payload *models.ItemCreatedResponse) *CreateSkuBundleCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku bundle created response +func (o *CreateSkuBundleCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuBundleCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateSkuBundleBadRequestCode is the HTTP code returned for type CreateSkuBundleBadRequest +const CreateSkuBundleBadRequestCode int = 400 + +/*CreateSkuBundleBadRequest invalid input, object invalid + +swagger:response createSkuBundleBadRequest +*/ +type CreateSkuBundleBadRequest struct { +} + +// NewCreateSkuBundleBadRequest creates CreateSkuBundleBadRequest with default headers values +func NewCreateSkuBundleBadRequest() *CreateSkuBundleBadRequest { + + return &CreateSkuBundleBadRequest{} +} + +// WriteResponse to the client +func (o *CreateSkuBundleBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// CreateSkuBundleConflictCode is the HTTP code returned for type CreateSkuBundleConflict +const CreateSkuBundleConflictCode int = 409 + +/*CreateSkuBundleConflict an existing item already exists + +swagger:response createSkuBundleConflict +*/ +type CreateSkuBundleConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateSkuBundleConflict creates CreateSkuBundleConflict with default headers values +func NewCreateSkuBundleConflict() *CreateSkuBundleConflict { + + return &CreateSkuBundleConflict{} +} + +// WithPayload adds the payload to the create sku bundle conflict response +func (o *CreateSkuBundleConflict) WithPayload(payload *models.ErrorResponse) *CreateSkuBundleConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku bundle conflict response +func (o *CreateSkuBundleConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuBundleConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateSkuBundleInternalServerErrorCode is the HTTP code returned for type CreateSkuBundleInternalServerError +const CreateSkuBundleInternalServerErrorCode int = 500 + +/*CreateSkuBundleInternalServerError unexpected error + +swagger:response createSkuBundleInternalServerError +*/ +type CreateSkuBundleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateSkuBundleInternalServerError creates CreateSkuBundleInternalServerError with default headers values +func NewCreateSkuBundleInternalServerError() *CreateSkuBundleInternalServerError { + + return &CreateSkuBundleInternalServerError{} +} + +// WithPayload adds the payload to the create sku bundle internal server error response +func (o *CreateSkuBundleInternalServerError) WithPayload(payload *models.ErrorResponse) *CreateSkuBundleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku bundle internal server error response +func (o *CreateSkuBundleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuBundleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_urlbuilder.go b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_urlbuilder.go new file mode 100644 index 0000000..386fdc5 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/create_sku_bundle_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// CreateSkuBundleURL generates an URL for the create sku bundle operation +type CreateSkuBundleURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateSkuBundleURL) WithBasePath(bp string) *CreateSkuBundleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateSkuBundleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *CreateSkuBundleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/bundle" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *CreateSkuBundleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *CreateSkuBundleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *CreateSkuBundleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on CreateSkuBundleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on CreateSkuBundleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *CreateSkuBundleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle.go new file mode 100644 index 0000000..c2d4aa9 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetSkuBundleHandlerFunc turns a function with the right signature into a get sku bundle handler +type GetSkuBundleHandlerFunc func(GetSkuBundleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetSkuBundleHandlerFunc) Handle(params GetSkuBundleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetSkuBundleHandler interface for that can handle valid get sku bundle params +type GetSkuBundleHandler interface { + Handle(GetSkuBundleParams, interface{}) middleware.Responder +} + +// NewGetSkuBundle creates a new http.Handler for the get sku bundle operation +func NewGetSkuBundle(ctx *middleware.Context, handler GetSkuBundleHandler) *GetSkuBundle { + return &GetSkuBundle{Context: ctx, Handler: handler} +} + +/*GetSkuBundle swagger:route GET /sku/bundle/{id} bundleManagement getSkuBundle + +Get specific sku bundle + +get sku bundle with given id + +*/ +type GetSkuBundle struct { + Context *middleware.Context + Handler GetSkuBundleHandler +} + +func (o *GetSkuBundle) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetSkuBundleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name.go new file mode 100644 index 0000000..9c483c7 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetSkuBundleByNameHandlerFunc turns a function with the right signature into a get sku bundle by name handler +type GetSkuBundleByNameHandlerFunc func(GetSkuBundleByNameParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetSkuBundleByNameHandlerFunc) Handle(params GetSkuBundleByNameParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetSkuBundleByNameHandler interface for that can handle valid get sku bundle by name params +type GetSkuBundleByNameHandler interface { + Handle(GetSkuBundleByNameParams, interface{}) middleware.Responder +} + +// NewGetSkuBundleByName creates a new http.Handler for the get sku bundle by name operation +func NewGetSkuBundleByName(ctx *middleware.Context, handler GetSkuBundleByNameHandler) *GetSkuBundleByName { + return &GetSkuBundleByName{Context: ctx, Handler: handler} +} + +/*GetSkuBundleByName swagger:route GET /sku/bundle/name/{name} bundleManagement getSkuBundleByName + +Get specific sku bundle + +get sku bundle with given name + +*/ +type GetSkuBundleByName struct { + Context *middleware.Context + Handler GetSkuBundleByNameHandler +} + +func (o *GetSkuBundleByName) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetSkuBundleByNameParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_parameters.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_parameters.go new file mode 100644 index 0000000..bbcdc46 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuBundleByNameParams creates a new GetSkuBundleByNameParams object +// no default values defined in spec. +func NewGetSkuBundleByNameParams() GetSkuBundleByNameParams { + + return GetSkuBundleByNameParams{} +} + +// GetSkuBundleByNameParams contains all the bound params for the get sku bundle by name operation +// typically these are obtained from a http.Request +// +// swagger:parameters getSkuBundleByName +type GetSkuBundleByNameParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of sku bundle to be obtained + Required: true + In: path + */ + Name string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetSkuBundleByNameParams() beforehand. +func (o *GetSkuBundleByNameParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rName, rhkName, _ := route.Params.GetOK("name") + if err := o.bindName(rName, rhkName, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindName binds and validates parameter Name from path. +func (o *GetSkuBundleByNameParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.Name = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_responses.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_responses.go new file mode 100644 index 0000000..9074808 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuBundleByNameOKCode is the HTTP code returned for type GetSkuBundleByNameOK +const GetSkuBundleByNameOKCode int = 200 + +/*GetSkuBundleByNameOK sku bundle returned + +swagger:response getSkuBundleByNameOK +*/ +type GetSkuBundleByNameOK struct { + + /* + In: Body + */ + Payload *models.SkuBundle `json:"body,omitempty"` +} + +// NewGetSkuBundleByNameOK creates GetSkuBundleByNameOK with default headers values +func NewGetSkuBundleByNameOK() *GetSkuBundleByNameOK { + + return &GetSkuBundleByNameOK{} +} + +// WithPayload adds the payload to the get sku bundle by name o k response +func (o *GetSkuBundleByNameOK) WithPayload(payload *models.SkuBundle) *GetSkuBundleByNameOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku bundle by name o k response +func (o *GetSkuBundleByNameOK) SetPayload(payload *models.SkuBundle) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuBundleByNameOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuBundleByNameNotFoundCode is the HTTP code returned for type GetSkuBundleByNameNotFound +const GetSkuBundleByNameNotFoundCode int = 404 + +/*GetSkuBundleByNameNotFound sku bundle with name not found + +swagger:response getSkuBundleByNameNotFound +*/ +type GetSkuBundleByNameNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuBundleByNameNotFound creates GetSkuBundleByNameNotFound with default headers values +func NewGetSkuBundleByNameNotFound() *GetSkuBundleByNameNotFound { + + return &GetSkuBundleByNameNotFound{} +} + +// WithPayload adds the payload to the get sku bundle by name not found response +func (o *GetSkuBundleByNameNotFound) WithPayload(payload *models.ErrorResponse) *GetSkuBundleByNameNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku bundle by name not found response +func (o *GetSkuBundleByNameNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuBundleByNameNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuBundleByNameInternalServerErrorCode is the HTTP code returned for type GetSkuBundleByNameInternalServerError +const GetSkuBundleByNameInternalServerErrorCode int = 500 + +/*GetSkuBundleByNameInternalServerError unexpected error + +swagger:response getSkuBundleByNameInternalServerError +*/ +type GetSkuBundleByNameInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuBundleByNameInternalServerError creates GetSkuBundleByNameInternalServerError with default headers values +func NewGetSkuBundleByNameInternalServerError() *GetSkuBundleByNameInternalServerError { + + return &GetSkuBundleByNameInternalServerError{} +} + +// WithPayload adds the payload to the get sku bundle by name internal server error response +func (o *GetSkuBundleByNameInternalServerError) WithPayload(payload *models.ErrorResponse) *GetSkuBundleByNameInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku bundle by name internal server error response +func (o *GetSkuBundleByNameInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuBundleByNameInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_urlbuilder.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_urlbuilder.go new file mode 100644 index 0000000..059de72 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_by_name_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetSkuBundleByNameURL generates an URL for the get sku bundle by name operation +type GetSkuBundleByNameURL struct { + Name string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuBundleByNameURL) WithBasePath(bp string) *GetSkuBundleByNameURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuBundleByNameURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetSkuBundleByNameURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/bundle/name/{name}" + + name := o.Name + if name != "" { + _path = strings.Replace(_path, "{name}", name, -1) + } else { + return nil, errors.New("name is required on GetSkuBundleByNameURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetSkuBundleByNameURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetSkuBundleByNameURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetSkuBundleByNameURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetSkuBundleByNameURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetSkuBundleByNameURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetSkuBundleByNameURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_parameters.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_parameters.go new file mode 100644 index 0000000..8642060 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuBundleParams creates a new GetSkuBundleParams object +// no default values defined in spec. +func NewGetSkuBundleParams() GetSkuBundleParams { + + return GetSkuBundleParams{} +} + +// GetSkuBundleParams contains all the bound params for the get sku bundle operation +// typically these are obtained from a http.Request +// +// swagger:parameters getSkuBundle +type GetSkuBundleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of sku bundle to be obtained + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetSkuBundleParams() beforehand. +func (o *GetSkuBundleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetSkuBundleParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_responses.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_responses.go new file mode 100644 index 0000000..0d085dd --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuBundleOKCode is the HTTP code returned for type GetSkuBundleOK +const GetSkuBundleOKCode int = 200 + +/*GetSkuBundleOK sku bundle returned + +swagger:response getSkuBundleOK +*/ +type GetSkuBundleOK struct { + + /* + In: Body + */ + Payload *models.SkuBundle `json:"body,omitempty"` +} + +// NewGetSkuBundleOK creates GetSkuBundleOK with default headers values +func NewGetSkuBundleOK() *GetSkuBundleOK { + + return &GetSkuBundleOK{} +} + +// WithPayload adds the payload to the get sku bundle o k response +func (o *GetSkuBundleOK) WithPayload(payload *models.SkuBundle) *GetSkuBundleOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku bundle o k response +func (o *GetSkuBundleOK) SetPayload(payload *models.SkuBundle) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuBundleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuBundleNotFoundCode is the HTTP code returned for type GetSkuBundleNotFound +const GetSkuBundleNotFoundCode int = 404 + +/*GetSkuBundleNotFound sku bundle with id not found + +swagger:response getSkuBundleNotFound +*/ +type GetSkuBundleNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuBundleNotFound creates GetSkuBundleNotFound with default headers values +func NewGetSkuBundleNotFound() *GetSkuBundleNotFound { + + return &GetSkuBundleNotFound{} +} + +// WithPayload adds the payload to the get sku bundle not found response +func (o *GetSkuBundleNotFound) WithPayload(payload *models.ErrorResponse) *GetSkuBundleNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku bundle not found response +func (o *GetSkuBundleNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuBundleNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuBundleInternalServerErrorCode is the HTTP code returned for type GetSkuBundleInternalServerError +const GetSkuBundleInternalServerErrorCode int = 500 + +/*GetSkuBundleInternalServerError unexpected error + +swagger:response getSkuBundleInternalServerError +*/ +type GetSkuBundleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuBundleInternalServerError creates GetSkuBundleInternalServerError with default headers values +func NewGetSkuBundleInternalServerError() *GetSkuBundleInternalServerError { + + return &GetSkuBundleInternalServerError{} +} + +// WithPayload adds the payload to the get sku bundle internal server error response +func (o *GetSkuBundleInternalServerError) WithPayload(payload *models.ErrorResponse) *GetSkuBundleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku bundle internal server error response +func (o *GetSkuBundleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuBundleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_urlbuilder.go b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_urlbuilder.go new file mode 100644 index 0000000..c251bbf --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/get_sku_bundle_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetSkuBundleURL generates an URL for the get sku bundle operation +type GetSkuBundleURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuBundleURL) WithBasePath(bp string) *GetSkuBundleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuBundleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetSkuBundleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/bundle/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetSkuBundleURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetSkuBundleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetSkuBundleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetSkuBundleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetSkuBundleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetSkuBundleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetSkuBundleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles.go b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles.go new file mode 100644 index 0000000..b77731d --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListSkuBundlesHandlerFunc turns a function with the right signature into a list sku bundles handler +type ListSkuBundlesHandlerFunc func(ListSkuBundlesParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListSkuBundlesHandlerFunc) Handle(params ListSkuBundlesParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListSkuBundlesHandler interface for that can handle valid list sku bundles params +type ListSkuBundlesHandler interface { + Handle(ListSkuBundlesParams, interface{}) middleware.Responder +} + +// NewListSkuBundles creates a new http.Handler for the list sku bundles operation +func NewListSkuBundles(ctx *middleware.Context, handler ListSkuBundlesHandler) *ListSkuBundles { + return &ListSkuBundles{Context: ctx, Handler: handler} +} + +/*ListSkuBundles swagger:route GET /sku/bundle bundleManagement listSkuBundles + +list SKU Bundles + +lists all sku bundles + +*/ +type ListSkuBundles struct { + Context *middleware.Context + Handler ListSkuBundlesHandler +} + +func (o *ListSkuBundles) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListSkuBundlesParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_parameters.go b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_parameters.go new file mode 100644 index 0000000..7b6c18b --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListSkuBundlesParams creates a new ListSkuBundlesParams object +// no default values defined in spec. +func NewListSkuBundlesParams() ListSkuBundlesParams { + + return ListSkuBundlesParams{} +} + +// ListSkuBundlesParams contains all the bound params for the list sku bundles operation +// typically these are obtained from a http.Request +// +// swagger:parameters listSkuBundles +type ListSkuBundlesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListSkuBundlesParams() beforehand. +func (o *ListSkuBundlesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_responses.go b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_responses.go new file mode 100644 index 0000000..8d43f75 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListSkuBundlesOKCode is the HTTP code returned for type ListSkuBundlesOK +const ListSkuBundlesOKCode int = 200 + +/*ListSkuBundlesOK list of skus bundles returned + +swagger:response listSkuBundlesOK +*/ +type ListSkuBundlesOK struct { + + /* + In: Body + */ + Payload []*models.SkuBundle `json:"body,omitempty"` +} + +// NewListSkuBundlesOK creates ListSkuBundlesOK with default headers values +func NewListSkuBundlesOK() *ListSkuBundlesOK { + + return &ListSkuBundlesOK{} +} + +// WithPayload adds the payload to the list sku bundles o k response +func (o *ListSkuBundlesOK) WithPayload(payload []*models.SkuBundle) *ListSkuBundlesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list sku bundles o k response +func (o *ListSkuBundlesOK) SetPayload(payload []*models.SkuBundle) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListSkuBundlesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.SkuBundle, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListSkuBundlesInternalServerErrorCode is the HTTP code returned for type ListSkuBundlesInternalServerError +const ListSkuBundlesInternalServerErrorCode int = 500 + +/*ListSkuBundlesInternalServerError unexpected error + +swagger:response listSkuBundlesInternalServerError +*/ +type ListSkuBundlesInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListSkuBundlesInternalServerError creates ListSkuBundlesInternalServerError with default headers values +func NewListSkuBundlesInternalServerError() *ListSkuBundlesInternalServerError { + + return &ListSkuBundlesInternalServerError{} +} + +// WithPayload adds the payload to the list sku bundles internal server error response +func (o *ListSkuBundlesInternalServerError) WithPayload(payload *models.ErrorResponse) *ListSkuBundlesInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list sku bundles internal server error response +func (o *ListSkuBundlesInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListSkuBundlesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_urlbuilder.go b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_urlbuilder.go new file mode 100644 index 0000000..dd8c44b --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/list_sku_bundles_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListSkuBundlesURL generates an URL for the list sku bundles operation +type ListSkuBundlesURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListSkuBundlesURL) WithBasePath(bp string) *ListSkuBundlesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListSkuBundlesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListSkuBundlesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/bundle" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListSkuBundlesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListSkuBundlesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListSkuBundlesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListSkuBundlesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListSkuBundlesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListSkuBundlesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle.go b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle.go new file mode 100644 index 0000000..551050f --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdateSkuBundleHandlerFunc turns a function with the right signature into a update sku bundle handler +type UpdateSkuBundleHandlerFunc func(UpdateSkuBundleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateSkuBundleHandlerFunc) Handle(params UpdateSkuBundleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdateSkuBundleHandler interface for that can handle valid update sku bundle params +type UpdateSkuBundleHandler interface { + Handle(UpdateSkuBundleParams, interface{}) middleware.Responder +} + +// NewUpdateSkuBundle creates a new http.Handler for the update sku bundle operation +func NewUpdateSkuBundle(ctx *middleware.Context, handler UpdateSkuBundleHandler) *UpdateSkuBundle { + return &UpdateSkuBundle{Context: ctx, Handler: handler} +} + +/*UpdateSkuBundle swagger:route PUT /sku/bundle/{id} bundleManagement updateSkuBundle + +Update specific sku bundle + +Update sku bundle with given id + +*/ +type UpdateSkuBundle struct { + Context *middleware.Context + Handler UpdateSkuBundleHandler +} + +func (o *UpdateSkuBundle) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateSkuBundleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_parameters.go b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_parameters.go new file mode 100644 index 0000000..01d4c98 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateSkuBundleParams creates a new UpdateSkuBundleParams object +// no default values defined in spec. +func NewUpdateSkuBundleParams() UpdateSkuBundleParams { + + return UpdateSkuBundleParams{} +} + +// UpdateSkuBundleParams contains all the bound params for the update sku bundle operation +// typically these are obtained from a http.Request +// +// swagger:parameters updateSkuBundle +type UpdateSkuBundleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*updated sku bundle containing all parameters except id + Required: true + In: body + */ + Bundle *models.SkuBundle + /*Id of sku bundle to be obtained + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateSkuBundleParams() beforehand. +func (o *UpdateSkuBundleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.SkuBundle + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("bundle", "body", "")) + } else { + res = append(res, errors.NewParseError("bundle", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Bundle = &body + } + } + } else { + res = append(res, errors.Required("bundle", "body", "")) + } + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdateSkuBundleParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_responses.go b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_responses.go new file mode 100644 index 0000000..3634221 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateSkuBundleOKCode is the HTTP code returned for type UpdateSkuBundleOK +const UpdateSkuBundleOKCode int = 200 + +/*UpdateSkuBundleOK updated sku bundle + +swagger:response updateSkuBundleOK +*/ +type UpdateSkuBundleOK struct { + + /* + In: Body + */ + Payload *models.SkuBundle `json:"body,omitempty"` +} + +// NewUpdateSkuBundleOK creates UpdateSkuBundleOK with default headers values +func NewUpdateSkuBundleOK() *UpdateSkuBundleOK { + + return &UpdateSkuBundleOK{} +} + +// WithPayload adds the payload to the update sku bundle o k response +func (o *UpdateSkuBundleOK) WithPayload(payload *models.SkuBundle) *UpdateSkuBundleOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku bundle o k response +func (o *UpdateSkuBundleOK) SetPayload(payload *models.SkuBundle) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuBundleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateSkuBundleNotFoundCode is the HTTP code returned for type UpdateSkuBundleNotFound +const UpdateSkuBundleNotFoundCode int = 404 + +/*UpdateSkuBundleNotFound sku bundle with id not found + +swagger:response updateSkuBundleNotFound +*/ +type UpdateSkuBundleNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateSkuBundleNotFound creates UpdateSkuBundleNotFound with default headers values +func NewUpdateSkuBundleNotFound() *UpdateSkuBundleNotFound { + + return &UpdateSkuBundleNotFound{} +} + +// WithPayload adds the payload to the update sku bundle not found response +func (o *UpdateSkuBundleNotFound) WithPayload(payload *models.ErrorResponse) *UpdateSkuBundleNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku bundle not found response +func (o *UpdateSkuBundleNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuBundleNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateSkuBundleInternalServerErrorCode is the HTTP code returned for type UpdateSkuBundleInternalServerError +const UpdateSkuBundleInternalServerErrorCode int = 500 + +/*UpdateSkuBundleInternalServerError unexpected error + +swagger:response updateSkuBundleInternalServerError +*/ +type UpdateSkuBundleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateSkuBundleInternalServerError creates UpdateSkuBundleInternalServerError with default headers values +func NewUpdateSkuBundleInternalServerError() *UpdateSkuBundleInternalServerError { + + return &UpdateSkuBundleInternalServerError{} +} + +// WithPayload adds the payload to the update sku bundle internal server error response +func (o *UpdateSkuBundleInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdateSkuBundleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku bundle internal server error response +func (o *UpdateSkuBundleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuBundleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_urlbuilder.go b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_urlbuilder.go new file mode 100644 index 0000000..477b083 --- /dev/null +++ b/services/plan-manager/restapi/operations/bundle_management/update_sku_bundle_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package bundle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdateSkuBundleURL generates an URL for the update sku bundle operation +type UpdateSkuBundleURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateSkuBundleURL) WithBasePath(bp string) *UpdateSkuBundleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateSkuBundleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateSkuBundleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/bundle/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdateSkuBundleURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateSkuBundleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateSkuBundleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateSkuBundleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateSkuBundleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateSkuBundleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateSkuBundleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/cycle_management/create_cycle.go b/services/plan-manager/restapi/operations/cycle_management/create_cycle.go new file mode 100644 index 0000000..cc702bd --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/create_cycle.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// CreateCycleHandlerFunc turns a function with the right signature into a create cycle handler +type CreateCycleHandlerFunc func(CreateCycleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn CreateCycleHandlerFunc) Handle(params CreateCycleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// CreateCycleHandler interface for that can handle valid create cycle params +type CreateCycleHandler interface { + Handle(CreateCycleParams, interface{}) middleware.Responder +} + +// NewCreateCycle creates a new http.Handler for the create cycle operation +func NewCreateCycle(ctx *middleware.Context, handler CreateCycleHandler) *CreateCycle { + return &CreateCycle{Context: ctx, Handler: handler} +} + +/*CreateCycle swagger:route POST /cycle cycleManagement createCycle + +Create a plan + +Creates a new cycle + +*/ +type CreateCycle struct { + Context *middleware.Context + Handler CreateCycleHandler +} + +func (o *CreateCycle) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewCreateCycleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/cycle_management/create_cycle_parameters.go b/services/plan-manager/restapi/operations/cycle_management/create_cycle_parameters.go new file mode 100644 index 0000000..c114a26 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/create_cycle_parameters.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateCycleParams creates a new CreateCycleParams object +// no default values defined in spec. +func NewCreateCycleParams() CreateCycleParams { + + return CreateCycleParams{} +} + +// CreateCycleParams contains all the bound params for the create cycle operation +// typically these are obtained from a http.Request +// +// swagger:parameters createCycle +type CreateCycleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Cycle to be added + In: body + */ + Cycle *models.Cycle +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewCreateCycleParams() beforehand. +func (o *CreateCycleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Cycle + if err := route.Consumer.Consume(r.Body, &body); err != nil { + res = append(res, errors.NewParseError("cycle", "body", "", err)) + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Cycle = &body + } + } + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/cycle_management/create_cycle_responses.go b/services/plan-manager/restapi/operations/cycle_management/create_cycle_responses.go new file mode 100644 index 0000000..ae77a66 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/create_cycle_responses.go @@ -0,0 +1,170 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateCycleCreatedCode is the HTTP code returned for type CreateCycleCreated +const CreateCycleCreatedCode int = 201 + +/*CreateCycleCreated item created + +swagger:response createCycleCreated +*/ +type CreateCycleCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewCreateCycleCreated creates CreateCycleCreated with default headers values +func NewCreateCycleCreated() *CreateCycleCreated { + + return &CreateCycleCreated{} +} + +// WithPayload adds the payload to the create cycle created response +func (o *CreateCycleCreated) WithPayload(payload *models.ItemCreatedResponse) *CreateCycleCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create cycle created response +func (o *CreateCycleCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateCycleCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateCycleBadRequestCode is the HTTP code returned for type CreateCycleBadRequest +const CreateCycleBadRequestCode int = 400 + +/*CreateCycleBadRequest invalid input, object invalid + +swagger:response createCycleBadRequest +*/ +type CreateCycleBadRequest struct { +} + +// NewCreateCycleBadRequest creates CreateCycleBadRequest with default headers values +func NewCreateCycleBadRequest() *CreateCycleBadRequest { + + return &CreateCycleBadRequest{} +} + +// WriteResponse to the client +func (o *CreateCycleBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// CreateCycleConflictCode is the HTTP code returned for type CreateCycleConflict +const CreateCycleConflictCode int = 409 + +/*CreateCycleConflict an existing item already exists + +swagger:response createCycleConflict +*/ +type CreateCycleConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateCycleConflict creates CreateCycleConflict with default headers values +func NewCreateCycleConflict() *CreateCycleConflict { + + return &CreateCycleConflict{} +} + +// WithPayload adds the payload to the create cycle conflict response +func (o *CreateCycleConflict) WithPayload(payload *models.ErrorResponse) *CreateCycleConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create cycle conflict response +func (o *CreateCycleConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateCycleConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateCycleInternalServerErrorCode is the HTTP code returned for type CreateCycleInternalServerError +const CreateCycleInternalServerErrorCode int = 500 + +/*CreateCycleInternalServerError unexpected error + +swagger:response createCycleInternalServerError +*/ +type CreateCycleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateCycleInternalServerError creates CreateCycleInternalServerError with default headers values +func NewCreateCycleInternalServerError() *CreateCycleInternalServerError { + + return &CreateCycleInternalServerError{} +} + +// WithPayload adds the payload to the create cycle internal server error response +func (o *CreateCycleInternalServerError) WithPayload(payload *models.ErrorResponse) *CreateCycleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create cycle internal server error response +func (o *CreateCycleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateCycleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/cycle_management/create_cycle_urlbuilder.go b/services/plan-manager/restapi/operations/cycle_management/create_cycle_urlbuilder.go new file mode 100644 index 0000000..0545470 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/create_cycle_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// CreateCycleURL generates an URL for the create cycle operation +type CreateCycleURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateCycleURL) WithBasePath(bp string) *CreateCycleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateCycleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *CreateCycleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/cycle" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *CreateCycleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *CreateCycleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *CreateCycleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on CreateCycleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on CreateCycleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *CreateCycleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/cycle_management/get_cycle.go b/services/plan-manager/restapi/operations/cycle_management/get_cycle.go new file mode 100644 index 0000000..d75fb10 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/get_cycle.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetCycleHandlerFunc turns a function with the right signature into a get cycle handler +type GetCycleHandlerFunc func(GetCycleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetCycleHandlerFunc) Handle(params GetCycleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetCycleHandler interface for that can handle valid get cycle params +type GetCycleHandler interface { + Handle(GetCycleParams, interface{}) middleware.Responder +} + +// NewGetCycle creates a new http.Handler for the get cycle operation +func NewGetCycle(ctx *middleware.Context, handler GetCycleHandler) *GetCycle { + return &GetCycle{Context: ctx, Handler: handler} +} + +/*GetCycle swagger:route GET /cycle/{id} cycleManagement getCycle + +Get specific cycle + +get cycle with given id + +*/ +type GetCycle struct { + Context *middleware.Context + Handler GetCycleHandler +} + +func (o *GetCycle) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetCycleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/cycle_management/get_cycle_parameters.go b/services/plan-manager/restapi/operations/cycle_management/get_cycle_parameters.go new file mode 100644 index 0000000..d2e94a3 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/get_cycle_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetCycleParams creates a new GetCycleParams object +// no default values defined in spec. +func NewGetCycleParams() GetCycleParams { + + return GetCycleParams{} +} + +// GetCycleParams contains all the bound params for the get cycle operation +// typically these are obtained from a http.Request +// +// swagger:parameters getCycle +type GetCycleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of cycle to be obtained + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetCycleParams() beforehand. +func (o *GetCycleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetCycleParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/cycle_management/get_cycle_responses.go b/services/plan-manager/restapi/operations/cycle_management/get_cycle_responses.go new file mode 100644 index 0000000..be380f5 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/get_cycle_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetCycleOKCode is the HTTP code returned for type GetCycleOK +const GetCycleOKCode int = 200 + +/*GetCycleOK cycle returned + +swagger:response getCycleOK +*/ +type GetCycleOK struct { + + /* + In: Body + */ + Payload *models.Cycle `json:"body,omitempty"` +} + +// NewGetCycleOK creates GetCycleOK with default headers values +func NewGetCycleOK() *GetCycleOK { + + return &GetCycleOK{} +} + +// WithPayload adds the payload to the get cycle o k response +func (o *GetCycleOK) WithPayload(payload *models.Cycle) *GetCycleOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get cycle o k response +func (o *GetCycleOK) SetPayload(payload *models.Cycle) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCycleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCycleNotFoundCode is the HTTP code returned for type GetCycleNotFound +const GetCycleNotFoundCode int = 404 + +/*GetCycleNotFound cycle with id not found + +swagger:response getCycleNotFound +*/ +type GetCycleNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCycleNotFound creates GetCycleNotFound with default headers values +func NewGetCycleNotFound() *GetCycleNotFound { + + return &GetCycleNotFound{} +} + +// WithPayload adds the payload to the get cycle not found response +func (o *GetCycleNotFound) WithPayload(payload *models.ErrorResponse) *GetCycleNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get cycle not found response +func (o *GetCycleNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCycleNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCycleInternalServerErrorCode is the HTTP code returned for type GetCycleInternalServerError +const GetCycleInternalServerErrorCode int = 500 + +/*GetCycleInternalServerError unexpected error + +swagger:response getCycleInternalServerError +*/ +type GetCycleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCycleInternalServerError creates GetCycleInternalServerError with default headers values +func NewGetCycleInternalServerError() *GetCycleInternalServerError { + + return &GetCycleInternalServerError{} +} + +// WithPayload adds the payload to the get cycle internal server error response +func (o *GetCycleInternalServerError) WithPayload(payload *models.ErrorResponse) *GetCycleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get cycle internal server error response +func (o *GetCycleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCycleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/cycle_management/get_cycle_urlbuilder.go b/services/plan-manager/restapi/operations/cycle_management/get_cycle_urlbuilder.go new file mode 100644 index 0000000..b4c2f0a --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/get_cycle_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetCycleURL generates an URL for the get cycle operation +type GetCycleURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCycleURL) WithBasePath(bp string) *GetCycleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCycleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetCycleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/cycle/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetCycleURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetCycleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetCycleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetCycleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetCycleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetCycleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetCycleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/cycle_management/list_cycles.go b/services/plan-manager/restapi/operations/cycle_management/list_cycles.go new file mode 100644 index 0000000..f40ed27 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/list_cycles.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListCyclesHandlerFunc turns a function with the right signature into a list cycles handler +type ListCyclesHandlerFunc func(ListCyclesParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListCyclesHandlerFunc) Handle(params ListCyclesParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListCyclesHandler interface for that can handle valid list cycles params +type ListCyclesHandler interface { + Handle(ListCyclesParams, interface{}) middleware.Responder +} + +// NewListCycles creates a new http.Handler for the list cycles operation +func NewListCycles(ctx *middleware.Context, handler ListCyclesHandler) *ListCycles { + return &ListCycles{Context: ctx, Handler: handler} +} + +/*ListCycles swagger:route GET /cycle cycleManagement listCycles + +List all cycles + +lists all cycles + +*/ +type ListCycles struct { + Context *middleware.Context + Handler ListCyclesHandler +} + +func (o *ListCycles) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListCyclesParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/cycle_management/list_cycles_parameters.go b/services/plan-manager/restapi/operations/cycle_management/list_cycles_parameters.go new file mode 100644 index 0000000..216aba2 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/list_cycles_parameters.go @@ -0,0 +1,104 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewListCyclesParams creates a new ListCyclesParams object +// no default values defined in spec. +func NewListCyclesParams() ListCyclesParams { + + return ListCyclesParams{} +} + +// ListCyclesParams contains all the bound params for the list cycles operation +// typically these are obtained from a http.Request +// +// swagger:parameters listCycles +type ListCyclesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*state to filter + In: query + */ + State *string + /*resource type to filter + In: query + */ + Type *string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListCyclesParams() beforehand. +func (o *ListCyclesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qState, qhkState, _ := qs.GetOK("state") + if err := o.bindState(qState, qhkState, route.Formats); err != nil { + res = append(res, err) + } + + qType, qhkType, _ := qs.GetOK("type") + if err := o.bindType(qType, qhkType, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindState binds and validates parameter State from query. +func (o *ListCyclesParams) bindState(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.State = &raw + + return nil +} + +// bindType binds and validates parameter Type from query. +func (o *ListCyclesParams) bindType(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Type = &raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/cycle_management/list_cycles_responses.go b/services/plan-manager/restapi/operations/cycle_management/list_cycles_responses.go new file mode 100644 index 0000000..b0574e7 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/list_cycles_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListCyclesOKCode is the HTTP code returned for type ListCyclesOK +const ListCyclesOKCode int = 200 + +/*ListCyclesOK list of cycles returned + +swagger:response listCyclesOK +*/ +type ListCyclesOK struct { + + /* + In: Body + */ + Payload []*models.Cycle `json:"body,omitempty"` +} + +// NewListCyclesOK creates ListCyclesOK with default headers values +func NewListCyclesOK() *ListCyclesOK { + + return &ListCyclesOK{} +} + +// WithPayload adds the payload to the list cycles o k response +func (o *ListCyclesOK) WithPayload(payload []*models.Cycle) *ListCyclesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list cycles o k response +func (o *ListCyclesOK) SetPayload(payload []*models.Cycle) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCyclesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Cycle, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListCyclesInternalServerErrorCode is the HTTP code returned for type ListCyclesInternalServerError +const ListCyclesInternalServerErrorCode int = 500 + +/*ListCyclesInternalServerError unexpected error + +swagger:response listCyclesInternalServerError +*/ +type ListCyclesInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListCyclesInternalServerError creates ListCyclesInternalServerError with default headers values +func NewListCyclesInternalServerError() *ListCyclesInternalServerError { + + return &ListCyclesInternalServerError{} +} + +// WithPayload adds the payload to the list cycles internal server error response +func (o *ListCyclesInternalServerError) WithPayload(payload *models.ErrorResponse) *ListCyclesInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list cycles internal server error response +func (o *ListCyclesInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCyclesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/cycle_management/list_cycles_urlbuilder.go b/services/plan-manager/restapi/operations/cycle_management/list_cycles_urlbuilder.go new file mode 100644 index 0000000..dd9a002 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/list_cycles_urlbuilder.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListCyclesURL generates an URL for the list cycles operation +type ListCyclesURL struct { + State *string + Type *string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCyclesURL) WithBasePath(bp string) *ListCyclesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCyclesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListCyclesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/cycle" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var stateQ string + if o.State != nil { + stateQ = *o.State + } + if stateQ != "" { + qs.Set("state", stateQ) + } + + var typeVarQ string + if o.Type != nil { + typeVarQ = *o.Type + } + if typeVarQ != "" { + qs.Set("type", typeVarQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListCyclesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListCyclesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListCyclesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListCyclesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListCyclesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListCyclesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/cycle_management/update_cycle.go b/services/plan-manager/restapi/operations/cycle_management/update_cycle.go new file mode 100644 index 0000000..8c70775 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/update_cycle.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdateCycleHandlerFunc turns a function with the right signature into a update cycle handler +type UpdateCycleHandlerFunc func(UpdateCycleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateCycleHandlerFunc) Handle(params UpdateCycleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdateCycleHandler interface for that can handle valid update cycle params +type UpdateCycleHandler interface { + Handle(UpdateCycleParams, interface{}) middleware.Responder +} + +// NewUpdateCycle creates a new http.Handler for the update cycle operation +func NewUpdateCycle(ctx *middleware.Context, handler UpdateCycleHandler) *UpdateCycle { + return &UpdateCycle{Context: ctx, Handler: handler} +} + +/*UpdateCycle swagger:route PUT /cycle/{id} cycleManagement updateCycle + +Update specific cycle + +Update cycle with given id + +*/ +type UpdateCycle struct { + Context *middleware.Context + Handler UpdateCycleHandler +} + +func (o *UpdateCycle) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateCycleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/cycle_management/update_cycle_parameters.go b/services/plan-manager/restapi/operations/cycle_management/update_cycle_parameters.go new file mode 100644 index 0000000..4cd48ca --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/update_cycle_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateCycleParams creates a new UpdateCycleParams object +// no default values defined in spec. +func NewUpdateCycleParams() UpdateCycleParams { + + return UpdateCycleParams{} +} + +// UpdateCycleParams contains all the bound params for the update cycle operation +// typically these are obtained from a http.Request +// +// swagger:parameters updateCycle +type UpdateCycleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*updated cycle containing all parameters except id + Required: true + In: body + */ + Cycle *models.Cycle + /*Id of cycle to be updated + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateCycleParams() beforehand. +func (o *UpdateCycleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Cycle + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("cycle", "body", "")) + } else { + res = append(res, errors.NewParseError("cycle", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Cycle = &body + } + } + } else { + res = append(res, errors.Required("cycle", "body", "")) + } + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdateCycleParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/cycle_management/update_cycle_responses.go b/services/plan-manager/restapi/operations/cycle_management/update_cycle_responses.go new file mode 100644 index 0000000..5b8f619 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/update_cycle_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateCycleOKCode is the HTTP code returned for type UpdateCycleOK +const UpdateCycleOKCode int = 200 + +/*UpdateCycleOK updated cycle + +swagger:response updateCycleOK +*/ +type UpdateCycleOK struct { + + /* + In: Body + */ + Payload *models.Cycle `json:"body,omitempty"` +} + +// NewUpdateCycleOK creates UpdateCycleOK with default headers values +func NewUpdateCycleOK() *UpdateCycleOK { + + return &UpdateCycleOK{} +} + +// WithPayload adds the payload to the update cycle o k response +func (o *UpdateCycleOK) WithPayload(payload *models.Cycle) *UpdateCycleOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update cycle o k response +func (o *UpdateCycleOK) SetPayload(payload *models.Cycle) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateCycleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateCycleNotFoundCode is the HTTP code returned for type UpdateCycleNotFound +const UpdateCycleNotFoundCode int = 404 + +/*UpdateCycleNotFound cycle with id not found + +swagger:response updateCycleNotFound +*/ +type UpdateCycleNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateCycleNotFound creates UpdateCycleNotFound with default headers values +func NewUpdateCycleNotFound() *UpdateCycleNotFound { + + return &UpdateCycleNotFound{} +} + +// WithPayload adds the payload to the update cycle not found response +func (o *UpdateCycleNotFound) WithPayload(payload *models.ErrorResponse) *UpdateCycleNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update cycle not found response +func (o *UpdateCycleNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateCycleNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateCycleInternalServerErrorCode is the HTTP code returned for type UpdateCycleInternalServerError +const UpdateCycleInternalServerErrorCode int = 500 + +/*UpdateCycleInternalServerError unexpected error + +swagger:response updateCycleInternalServerError +*/ +type UpdateCycleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateCycleInternalServerError creates UpdateCycleInternalServerError with default headers values +func NewUpdateCycleInternalServerError() *UpdateCycleInternalServerError { + + return &UpdateCycleInternalServerError{} +} + +// WithPayload adds the payload to the update cycle internal server error response +func (o *UpdateCycleInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdateCycleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update cycle internal server error response +func (o *UpdateCycleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateCycleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/cycle_management/update_cycle_urlbuilder.go b/services/plan-manager/restapi/operations/cycle_management/update_cycle_urlbuilder.go new file mode 100644 index 0000000..ed02767 --- /dev/null +++ b/services/plan-manager/restapi/operations/cycle_management/update_cycle_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package cycle_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdateCycleURL generates an URL for the update cycle operation +type UpdateCycleURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateCycleURL) WithBasePath(bp string) *UpdateCycleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateCycleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateCycleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/cycle/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdateCycleURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateCycleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateCycleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateCycleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateCycleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateCycleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateCycleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/plan_management/create_plan.go b/services/plan-manager/restapi/operations/plan_management/create_plan.go new file mode 100644 index 0000000..d02a778 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/create_plan.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// CreatePlanHandlerFunc turns a function with the right signature into a create plan handler +type CreatePlanHandlerFunc func(CreatePlanParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn CreatePlanHandlerFunc) Handle(params CreatePlanParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// CreatePlanHandler interface for that can handle valid create plan params +type CreatePlanHandler interface { + Handle(CreatePlanParams, interface{}) middleware.Responder +} + +// NewCreatePlan creates a new http.Handler for the create plan operation +func NewCreatePlan(ctx *middleware.Context, handler CreatePlanHandler) *CreatePlan { + return &CreatePlan{Context: ctx, Handler: handler} +} + +/*CreatePlan swagger:route POST /plan planManagement createPlan + +Create a plan + +Creates a new plan + +*/ +type CreatePlan struct { + Context *middleware.Context + Handler CreatePlanHandler +} + +func (o *CreatePlan) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewCreatePlanParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/plan_management/create_plan_parameters.go b/services/plan-manager/restapi/operations/plan_management/create_plan_parameters.go new file mode 100644 index 0000000..fc6bc2c --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/create_plan_parameters.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreatePlanParams creates a new CreatePlanParams object +// no default values defined in spec. +func NewCreatePlanParams() CreatePlanParams { + + return CreatePlanParams{} +} + +// CreatePlanParams contains all the bound params for the create plan operation +// typically these are obtained from a http.Request +// +// swagger:parameters createPlan +type CreatePlanParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Plan to be added + In: body + */ + Plan *models.Plan +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewCreatePlanParams() beforehand. +func (o *CreatePlanParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Plan + if err := route.Consumer.Consume(r.Body, &body); err != nil { + res = append(res, errors.NewParseError("plan", "body", "", err)) + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Plan = &body + } + } + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/plan_management/create_plan_responses.go b/services/plan-manager/restapi/operations/plan_management/create_plan_responses.go new file mode 100644 index 0000000..f481946 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/create_plan_responses.go @@ -0,0 +1,170 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreatePlanCreatedCode is the HTTP code returned for type CreatePlanCreated +const CreatePlanCreatedCode int = 201 + +/*CreatePlanCreated item created + +swagger:response createPlanCreated +*/ +type CreatePlanCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewCreatePlanCreated creates CreatePlanCreated with default headers values +func NewCreatePlanCreated() *CreatePlanCreated { + + return &CreatePlanCreated{} +} + +// WithPayload adds the payload to the create plan created response +func (o *CreatePlanCreated) WithPayload(payload *models.ItemCreatedResponse) *CreatePlanCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create plan created response +func (o *CreatePlanCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreatePlanCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreatePlanBadRequestCode is the HTTP code returned for type CreatePlanBadRequest +const CreatePlanBadRequestCode int = 400 + +/*CreatePlanBadRequest invalid input, object invalid + +swagger:response createPlanBadRequest +*/ +type CreatePlanBadRequest struct { +} + +// NewCreatePlanBadRequest creates CreatePlanBadRequest with default headers values +func NewCreatePlanBadRequest() *CreatePlanBadRequest { + + return &CreatePlanBadRequest{} +} + +// WriteResponse to the client +func (o *CreatePlanBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// CreatePlanConflictCode is the HTTP code returned for type CreatePlanConflict +const CreatePlanConflictCode int = 409 + +/*CreatePlanConflict an existing item already exists + +swagger:response createPlanConflict +*/ +type CreatePlanConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreatePlanConflict creates CreatePlanConflict with default headers values +func NewCreatePlanConflict() *CreatePlanConflict { + + return &CreatePlanConflict{} +} + +// WithPayload adds the payload to the create plan conflict response +func (o *CreatePlanConflict) WithPayload(payload *models.ErrorResponse) *CreatePlanConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create plan conflict response +func (o *CreatePlanConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreatePlanConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreatePlanInternalServerErrorCode is the HTTP code returned for type CreatePlanInternalServerError +const CreatePlanInternalServerErrorCode int = 500 + +/*CreatePlanInternalServerError unexpected error + +swagger:response createPlanInternalServerError +*/ +type CreatePlanInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreatePlanInternalServerError creates CreatePlanInternalServerError with default headers values +func NewCreatePlanInternalServerError() *CreatePlanInternalServerError { + + return &CreatePlanInternalServerError{} +} + +// WithPayload adds the payload to the create plan internal server error response +func (o *CreatePlanInternalServerError) WithPayload(payload *models.ErrorResponse) *CreatePlanInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create plan internal server error response +func (o *CreatePlanInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreatePlanInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/plan_management/create_plan_urlbuilder.go b/services/plan-manager/restapi/operations/plan_management/create_plan_urlbuilder.go new file mode 100644 index 0000000..9dae82d --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/create_plan_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// CreatePlanURL generates an URL for the create plan operation +type CreatePlanURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreatePlanURL) WithBasePath(bp string) *CreatePlanURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreatePlanURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *CreatePlanURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/plan" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *CreatePlanURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *CreatePlanURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *CreatePlanURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on CreatePlanURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on CreatePlanURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *CreatePlanURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_complete_plan.go b/services/plan-manager/restapi/operations/plan_management/get_complete_plan.go new file mode 100644 index 0000000..a871c42 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_complete_plan.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetCompletePlanHandlerFunc turns a function with the right signature into a get complete plan handler +type GetCompletePlanHandlerFunc func(GetCompletePlanParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetCompletePlanHandlerFunc) Handle(params GetCompletePlanParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetCompletePlanHandler interface for that can handle valid get complete plan params +type GetCompletePlanHandler interface { + Handle(GetCompletePlanParams, interface{}) middleware.Responder +} + +// NewGetCompletePlan creates a new http.Handler for the get complete plan operation +func NewGetCompletePlan(ctx *middleware.Context, handler GetCompletePlanHandler) *GetCompletePlan { + return &GetCompletePlan{Context: ctx, Handler: handler} +} + +/*GetCompletePlan swagger:route GET /plan/complete/{id} planManagement getCompletePlan + +Get complete plan + +gets complete plan with planid + +*/ +type GetCompletePlan struct { + Context *middleware.Context + Handler GetCompletePlanHandler +} + +func (o *GetCompletePlan) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetCompletePlanParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_complete_plan_parameters.go b/services/plan-manager/restapi/operations/plan_management/get_complete_plan_parameters.go new file mode 100644 index 0000000..400e17c --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_complete_plan_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetCompletePlanParams creates a new GetCompletePlanParams object +// no default values defined in spec. +func NewGetCompletePlanParams() GetCompletePlanParams { + + return GetCompletePlanParams{} +} + +// GetCompletePlanParams contains all the bound params for the get complete plan operation +// typically these are obtained from a http.Request +// +// swagger:parameters getCompletePlan +type GetCompletePlanParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of plan to be obtained + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetCompletePlanParams() beforehand. +func (o *GetCompletePlanParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetCompletePlanParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_complete_plan_responses.go b/services/plan-manager/restapi/operations/plan_management/get_complete_plan_responses.go new file mode 100644 index 0000000..ec22c5c --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_complete_plan_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetCompletePlanOKCode is the HTTP code returned for type GetCompletePlanOK +const GetCompletePlanOKCode int = 200 + +/*GetCompletePlanOK plan returned + +swagger:response getCompletePlanOK +*/ +type GetCompletePlanOK struct { + + /* + In: Body + */ + Payload *models.Plan `json:"body,omitempty"` +} + +// NewGetCompletePlanOK creates GetCompletePlanOK with default headers values +func NewGetCompletePlanOK() *GetCompletePlanOK { + + return &GetCompletePlanOK{} +} + +// WithPayload adds the payload to the get complete plan o k response +func (o *GetCompletePlanOK) WithPayload(payload *models.Plan) *GetCompletePlanOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get complete plan o k response +func (o *GetCompletePlanOK) SetPayload(payload *models.Plan) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCompletePlanOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCompletePlanNotFoundCode is the HTTP code returned for type GetCompletePlanNotFound +const GetCompletePlanNotFoundCode int = 404 + +/*GetCompletePlanNotFound complete plan with planid not found + +swagger:response getCompletePlanNotFound +*/ +type GetCompletePlanNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCompletePlanNotFound creates GetCompletePlanNotFound with default headers values +func NewGetCompletePlanNotFound() *GetCompletePlanNotFound { + + return &GetCompletePlanNotFound{} +} + +// WithPayload adds the payload to the get complete plan not found response +func (o *GetCompletePlanNotFound) WithPayload(payload *models.ErrorResponse) *GetCompletePlanNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get complete plan not found response +func (o *GetCompletePlanNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCompletePlanNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetCompletePlanInternalServerErrorCode is the HTTP code returned for type GetCompletePlanInternalServerError +const GetCompletePlanInternalServerErrorCode int = 500 + +/*GetCompletePlanInternalServerError unexpected error + +swagger:response getCompletePlanInternalServerError +*/ +type GetCompletePlanInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetCompletePlanInternalServerError creates GetCompletePlanInternalServerError with default headers values +func NewGetCompletePlanInternalServerError() *GetCompletePlanInternalServerError { + + return &GetCompletePlanInternalServerError{} +} + +// WithPayload adds the payload to the get complete plan internal server error response +func (o *GetCompletePlanInternalServerError) WithPayload(payload *models.ErrorResponse) *GetCompletePlanInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get complete plan internal server error response +func (o *GetCompletePlanInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetCompletePlanInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_complete_plan_urlbuilder.go b/services/plan-manager/restapi/operations/plan_management/get_complete_plan_urlbuilder.go new file mode 100644 index 0000000..7733e80 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_complete_plan_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetCompletePlanURL generates an URL for the get complete plan operation +type GetCompletePlanURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCompletePlanURL) WithBasePath(bp string) *GetCompletePlanURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetCompletePlanURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetCompletePlanURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/plan/complete/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetCompletePlanURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetCompletePlanURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetCompletePlanURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetCompletePlanURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetCompletePlanURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetCompletePlanURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetCompletePlanURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_plan.go b/services/plan-manager/restapi/operations/plan_management/get_plan.go new file mode 100644 index 0000000..0fd5dfe --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_plan.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetPlanHandlerFunc turns a function with the right signature into a get plan handler +type GetPlanHandlerFunc func(GetPlanParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetPlanHandlerFunc) Handle(params GetPlanParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetPlanHandler interface for that can handle valid get plan params +type GetPlanHandler interface { + Handle(GetPlanParams, interface{}) middleware.Responder +} + +// NewGetPlan creates a new http.Handler for the get plan operation +func NewGetPlan(ctx *middleware.Context, handler GetPlanHandler) *GetPlan { + return &GetPlan{Context: ctx, Handler: handler} +} + +/*GetPlan swagger:route GET /plan/{id} planManagement getPlan + +Get specific plan + +get plan with given planid + +*/ +type GetPlan struct { + Context *middleware.Context + Handler GetPlanHandler +} + +func (o *GetPlan) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetPlanParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_plan_parameters.go b/services/plan-manager/restapi/operations/plan_management/get_plan_parameters.go new file mode 100644 index 0000000..dea17f4 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_plan_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetPlanParams creates a new GetPlanParams object +// no default values defined in spec. +func NewGetPlanParams() GetPlanParams { + + return GetPlanParams{} +} + +// GetPlanParams contains all the bound params for the get plan operation +// typically these are obtained from a http.Request +// +// swagger:parameters getPlan +type GetPlanParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of plan to be obtained + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetPlanParams() beforehand. +func (o *GetPlanParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetPlanParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_plan_responses.go b/services/plan-manager/restapi/operations/plan_management/get_plan_responses.go new file mode 100644 index 0000000..07bee47 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_plan_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetPlanOKCode is the HTTP code returned for type GetPlanOK +const GetPlanOKCode int = 200 + +/*GetPlanOK plan returned + +swagger:response getPlanOK +*/ +type GetPlanOK struct { + + /* + In: Body + */ + Payload *models.Plan `json:"body,omitempty"` +} + +// NewGetPlanOK creates GetPlanOK with default headers values +func NewGetPlanOK() *GetPlanOK { + + return &GetPlanOK{} +} + +// WithPayload adds the payload to the get plan o k response +func (o *GetPlanOK) WithPayload(payload *models.Plan) *GetPlanOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get plan o k response +func (o *GetPlanOK) SetPayload(payload *models.Plan) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetPlanOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetPlanNotFoundCode is the HTTP code returned for type GetPlanNotFound +const GetPlanNotFoundCode int = 404 + +/*GetPlanNotFound plan with planid not found + +swagger:response getPlanNotFound +*/ +type GetPlanNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetPlanNotFound creates GetPlanNotFound with default headers values +func NewGetPlanNotFound() *GetPlanNotFound { + + return &GetPlanNotFound{} +} + +// WithPayload adds the payload to the get plan not found response +func (o *GetPlanNotFound) WithPayload(payload *models.ErrorResponse) *GetPlanNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get plan not found response +func (o *GetPlanNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetPlanNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetPlanInternalServerErrorCode is the HTTP code returned for type GetPlanInternalServerError +const GetPlanInternalServerErrorCode int = 500 + +/*GetPlanInternalServerError unexpected error + +swagger:response getPlanInternalServerError +*/ +type GetPlanInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetPlanInternalServerError creates GetPlanInternalServerError with default headers values +func NewGetPlanInternalServerError() *GetPlanInternalServerError { + + return &GetPlanInternalServerError{} +} + +// WithPayload adds the payload to the get plan internal server error response +func (o *GetPlanInternalServerError) WithPayload(payload *models.ErrorResponse) *GetPlanInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get plan internal server error response +func (o *GetPlanInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetPlanInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/plan_management/get_plan_urlbuilder.go b/services/plan-manager/restapi/operations/plan_management/get_plan_urlbuilder.go new file mode 100644 index 0000000..d74891d --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/get_plan_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetPlanURL generates an URL for the get plan operation +type GetPlanURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetPlanURL) WithBasePath(bp string) *GetPlanURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetPlanURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetPlanURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/plan/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetPlanURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetPlanURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetPlanURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetPlanURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetPlanURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetPlanURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetPlanURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_complete_plans.go b/services/plan-manager/restapi/operations/plan_management/list_complete_plans.go new file mode 100644 index 0000000..b5daa4d --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_complete_plans.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListCompletePlansHandlerFunc turns a function with the right signature into a list complete plans handler +type ListCompletePlansHandlerFunc func(ListCompletePlansParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListCompletePlansHandlerFunc) Handle(params ListCompletePlansParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListCompletePlansHandler interface for that can handle valid list complete plans params +type ListCompletePlansHandler interface { + Handle(ListCompletePlansParams, interface{}) middleware.Responder +} + +// NewListCompletePlans creates a new http.Handler for the list complete plans operation +func NewListCompletePlans(ctx *middleware.Context, handler ListCompletePlansHandler) *ListCompletePlans { + return &ListCompletePlans{Context: ctx, Handler: handler} +} + +/*ListCompletePlans swagger:route GET /plan/complete planManagement listCompletePlans + +Get full information relating to known plans + +Obtains full information on all known plans + +*/ +type ListCompletePlans struct { + Context *middleware.Context + Handler ListCompletePlansHandler +} + +func (o *ListCompletePlans) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListCompletePlansParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_complete_plans_parameters.go b/services/plan-manager/restapi/operations/plan_management/list_complete_plans_parameters.go new file mode 100644 index 0000000..b2d6d71 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_complete_plans_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListCompletePlansParams creates a new ListCompletePlansParams object +// no default values defined in spec. +func NewListCompletePlansParams() ListCompletePlansParams { + + return ListCompletePlansParams{} +} + +// ListCompletePlansParams contains all the bound params for the list complete plans operation +// typically these are obtained from a http.Request +// +// swagger:parameters listCompletePlans +type ListCompletePlansParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListCompletePlansParams() beforehand. +func (o *ListCompletePlansParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_complete_plans_responses.go b/services/plan-manager/restapi/operations/plan_management/list_complete_plans_responses.go new file mode 100644 index 0000000..7a8e83c --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_complete_plans_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListCompletePlansOKCode is the HTTP code returned for type ListCompletePlansOK +const ListCompletePlansOKCode int = 200 + +/*ListCompletePlansOK Set of known plans returned in full + +swagger:response listCompletePlansOK +*/ +type ListCompletePlansOK struct { + + /* + In: Body + */ + Payload []*models.Plan `json:"body,omitempty"` +} + +// NewListCompletePlansOK creates ListCompletePlansOK with default headers values +func NewListCompletePlansOK() *ListCompletePlansOK { + + return &ListCompletePlansOK{} +} + +// WithPayload adds the payload to the list complete plans o k response +func (o *ListCompletePlansOK) WithPayload(payload []*models.Plan) *ListCompletePlansOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list complete plans o k response +func (o *ListCompletePlansOK) SetPayload(payload []*models.Plan) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCompletePlansOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Plan, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListCompletePlansInternalServerErrorCode is the HTTP code returned for type ListCompletePlansInternalServerError +const ListCompletePlansInternalServerErrorCode int = 500 + +/*ListCompletePlansInternalServerError unexpected error + +swagger:response listCompletePlansInternalServerError +*/ +type ListCompletePlansInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListCompletePlansInternalServerError creates ListCompletePlansInternalServerError with default headers values +func NewListCompletePlansInternalServerError() *ListCompletePlansInternalServerError { + + return &ListCompletePlansInternalServerError{} +} + +// WithPayload adds the payload to the list complete plans internal server error response +func (o *ListCompletePlansInternalServerError) WithPayload(payload *models.ErrorResponse) *ListCompletePlansInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list complete plans internal server error response +func (o *ListCompletePlansInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListCompletePlansInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_complete_plans_urlbuilder.go b/services/plan-manager/restapi/operations/plan_management/list_complete_plans_urlbuilder.go new file mode 100644 index 0000000..daa857f --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_complete_plans_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListCompletePlansURL generates an URL for the list complete plans operation +type ListCompletePlansURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCompletePlansURL) WithBasePath(bp string) *ListCompletePlansURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListCompletePlansURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListCompletePlansURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/plan/complete" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListCompletePlansURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListCompletePlansURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListCompletePlansURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListCompletePlansURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListCompletePlansURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListCompletePlansURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_plans.go b/services/plan-manager/restapi/operations/plan_management/list_plans.go new file mode 100644 index 0000000..e95e774 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_plans.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListPlansHandlerFunc turns a function with the right signature into a list plans handler +type ListPlansHandlerFunc func(ListPlansParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListPlansHandlerFunc) Handle(params ListPlansParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListPlansHandler interface for that can handle valid list plans params +type ListPlansHandler interface { + Handle(ListPlansParams, interface{}) middleware.Responder +} + +// NewListPlans creates a new http.Handler for the list plans operation +func NewListPlans(ctx *middleware.Context, handler ListPlansHandler) *ListPlans { + return &ListPlans{Context: ctx, Handler: handler} +} + +/*ListPlans swagger:route GET /plan planManagement listPlans + +List all plans + +lists all plans (tbd - pagination?) + +*/ +type ListPlans struct { + Context *middleware.Context + Handler ListPlansHandler +} + +func (o *ListPlans) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListPlansParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_plans_parameters.go b/services/plan-manager/restapi/operations/plan_management/list_plans_parameters.go new file mode 100644 index 0000000..2e8e238 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_plans_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListPlansParams creates a new ListPlansParams object +// no default values defined in spec. +func NewListPlansParams() ListPlansParams { + + return ListPlansParams{} +} + +// ListPlansParams contains all the bound params for the list plans operation +// typically these are obtained from a http.Request +// +// swagger:parameters listPlans +type ListPlansParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListPlansParams() beforehand. +func (o *ListPlansParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_plans_responses.go b/services/plan-manager/restapi/operations/plan_management/list_plans_responses.go new file mode 100644 index 0000000..04e5eb6 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_plans_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListPlansOKCode is the HTTP code returned for type ListPlansOK +const ListPlansOKCode int = 200 + +/*ListPlansOK list of plans returned + +swagger:response listPlansOK +*/ +type ListPlansOK struct { + + /* + In: Body + */ + Payload []*models.Plan `json:"body,omitempty"` +} + +// NewListPlansOK creates ListPlansOK with default headers values +func NewListPlansOK() *ListPlansOK { + + return &ListPlansOK{} +} + +// WithPayload adds the payload to the list plans o k response +func (o *ListPlansOK) WithPayload(payload []*models.Plan) *ListPlansOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list plans o k response +func (o *ListPlansOK) SetPayload(payload []*models.Plan) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListPlansOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Plan, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListPlansInternalServerErrorCode is the HTTP code returned for type ListPlansInternalServerError +const ListPlansInternalServerErrorCode int = 500 + +/*ListPlansInternalServerError unexpected error + +swagger:response listPlansInternalServerError +*/ +type ListPlansInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListPlansInternalServerError creates ListPlansInternalServerError with default headers values +func NewListPlansInternalServerError() *ListPlansInternalServerError { + + return &ListPlansInternalServerError{} +} + +// WithPayload adds the payload to the list plans internal server error response +func (o *ListPlansInternalServerError) WithPayload(payload *models.ErrorResponse) *ListPlansInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list plans internal server error response +func (o *ListPlansInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListPlansInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/plan_management/list_plans_urlbuilder.go b/services/plan-manager/restapi/operations/plan_management/list_plans_urlbuilder.go new file mode 100644 index 0000000..bd8435e --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/list_plans_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListPlansURL generates an URL for the list plans operation +type ListPlansURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListPlansURL) WithBasePath(bp string) *ListPlansURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListPlansURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListPlansURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/plan" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListPlansURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListPlansURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListPlansURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListPlansURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListPlansURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListPlansURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/plan_management/update_plan.go b/services/plan-manager/restapi/operations/plan_management/update_plan.go new file mode 100644 index 0000000..c50afe3 --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/update_plan.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdatePlanHandlerFunc turns a function with the right signature into a update plan handler +type UpdatePlanHandlerFunc func(UpdatePlanParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdatePlanHandlerFunc) Handle(params UpdatePlanParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdatePlanHandler interface for that can handle valid update plan params +type UpdatePlanHandler interface { + Handle(UpdatePlanParams, interface{}) middleware.Responder +} + +// NewUpdatePlan creates a new http.Handler for the update plan operation +func NewUpdatePlan(ctx *middleware.Context, handler UpdatePlanHandler) *UpdatePlan { + return &UpdatePlan{Context: ctx, Handler: handler} +} + +/*UpdatePlan swagger:route PUT /plan/{id} planManagement updatePlan + +Update specific plan + +Update plan with given planId + +*/ +type UpdatePlan struct { + Context *middleware.Context + Handler UpdatePlanHandler +} + +func (o *UpdatePlan) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdatePlanParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/plan_management/update_plan_parameters.go b/services/plan-manager/restapi/operations/plan_management/update_plan_parameters.go new file mode 100644 index 0000000..abd9bdf --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/update_plan_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdatePlanParams creates a new UpdatePlanParams object +// no default values defined in spec. +func NewUpdatePlanParams() UpdatePlanParams { + + return UpdatePlanParams{} +} + +// UpdatePlanParams contains all the bound params for the update plan operation +// typically these are obtained from a http.Request +// +// swagger:parameters updatePlan +type UpdatePlanParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of plan to be obtained + Required: true + In: path + */ + ID string + /*updated plan containing all parameters except id + Required: true + In: body + */ + Plan *models.Plan +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdatePlanParams() beforehand. +func (o *UpdatePlanParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Plan + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("plan", "body", "")) + } else { + res = append(res, errors.NewParseError("plan", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Plan = &body + } + } + } else { + res = append(res, errors.Required("plan", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdatePlanParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/plan_management/update_plan_responses.go b/services/plan-manager/restapi/operations/plan_management/update_plan_responses.go new file mode 100644 index 0000000..855e9bb --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/update_plan_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdatePlanOKCode is the HTTP code returned for type UpdatePlanOK +const UpdatePlanOKCode int = 200 + +/*UpdatePlanOK updated plan + +swagger:response updatePlanOK +*/ +type UpdatePlanOK struct { + + /* + In: Body + */ + Payload *models.Plan `json:"body,omitempty"` +} + +// NewUpdatePlanOK creates UpdatePlanOK with default headers values +func NewUpdatePlanOK() *UpdatePlanOK { + + return &UpdatePlanOK{} +} + +// WithPayload adds the payload to the update plan o k response +func (o *UpdatePlanOK) WithPayload(payload *models.Plan) *UpdatePlanOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update plan o k response +func (o *UpdatePlanOK) SetPayload(payload *models.Plan) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdatePlanOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdatePlanNotFoundCode is the HTTP code returned for type UpdatePlanNotFound +const UpdatePlanNotFoundCode int = 404 + +/*UpdatePlanNotFound plan with planid not found + +swagger:response updatePlanNotFound +*/ +type UpdatePlanNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdatePlanNotFound creates UpdatePlanNotFound with default headers values +func NewUpdatePlanNotFound() *UpdatePlanNotFound { + + return &UpdatePlanNotFound{} +} + +// WithPayload adds the payload to the update plan not found response +func (o *UpdatePlanNotFound) WithPayload(payload *models.ErrorResponse) *UpdatePlanNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update plan not found response +func (o *UpdatePlanNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdatePlanNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdatePlanInternalServerErrorCode is the HTTP code returned for type UpdatePlanInternalServerError +const UpdatePlanInternalServerErrorCode int = 500 + +/*UpdatePlanInternalServerError unexpected error + +swagger:response updatePlanInternalServerError +*/ +type UpdatePlanInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdatePlanInternalServerError creates UpdatePlanInternalServerError with default headers values +func NewUpdatePlanInternalServerError() *UpdatePlanInternalServerError { + + return &UpdatePlanInternalServerError{} +} + +// WithPayload adds the payload to the update plan internal server error response +func (o *UpdatePlanInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdatePlanInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update plan internal server error response +func (o *UpdatePlanInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdatePlanInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/plan_management/update_plan_urlbuilder.go b/services/plan-manager/restapi/operations/plan_management/update_plan_urlbuilder.go new file mode 100644 index 0000000..787ddef --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_management/update_plan_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package plan_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdatePlanURL generates an URL for the update plan operation +type UpdatePlanURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdatePlanURL) WithBasePath(bp string) *UpdatePlanURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdatePlanURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdatePlanURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/plan/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdatePlanURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdatePlanURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdatePlanURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdatePlanURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdatePlanURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdatePlanURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdatePlanURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/plan_manager_management_api_api.go b/services/plan-manager/restapi/operations/plan_manager_management_api_api.go new file mode 100644 index 0000000..c44ac8b --- /dev/null +++ b/services/plan-manager/restapi/operations/plan_manager_management_api_api.go @@ -0,0 +1,661 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/bundle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/cycle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/plan_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/price_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/sku_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/trigger_management" +) + +// NewPlanManagerManagementAPIAPI creates a new PlanManagerManagementAPI instance +func NewPlanManagerManagementAPIAPI(spec *loads.Document) *PlanManagerManagementAPIAPI { + return &PlanManagerManagementAPIAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + useSwaggerUI: false, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + CycleManagementCreateCycleHandler: cycle_management.CreateCycleHandlerFunc(func(params cycle_management.CreateCycleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation cycle_management.CreateCycle has not yet been implemented") + }), + PlanManagementCreatePlanHandler: plan_management.CreatePlanHandlerFunc(func(params plan_management.CreatePlanParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation plan_management.CreatePlan has not yet been implemented") + }), + SkuManagementCreateSkuHandler: sku_management.CreateSkuHandlerFunc(func(params sku_management.CreateSkuParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation sku_management.CreateSku has not yet been implemented") + }), + BundleManagementCreateSkuBundleHandler: bundle_management.CreateSkuBundleHandlerFunc(func(params bundle_management.CreateSkuBundleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bundle_management.CreateSkuBundle has not yet been implemented") + }), + PriceManagementCreateSkuPriceHandler: price_management.CreateSkuPriceHandlerFunc(func(params price_management.CreateSkuPriceParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation price_management.CreateSkuPrice has not yet been implemented") + }), + TriggerManagementExecSampleHandler: trigger_management.ExecSampleHandlerFunc(func(params trigger_management.ExecSampleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.ExecSample has not yet been implemented") + }), + PlanManagementGetCompletePlanHandler: plan_management.GetCompletePlanHandlerFunc(func(params plan_management.GetCompletePlanParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation plan_management.GetCompletePlan has not yet been implemented") + }), + CycleManagementGetCycleHandler: cycle_management.GetCycleHandlerFunc(func(params cycle_management.GetCycleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation cycle_management.GetCycle has not yet been implemented") + }), + PlanManagementGetPlanHandler: plan_management.GetPlanHandlerFunc(func(params plan_management.GetPlanParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation plan_management.GetPlan has not yet been implemented") + }), + SkuManagementGetSkuHandler: sku_management.GetSkuHandlerFunc(func(params sku_management.GetSkuParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation sku_management.GetSku has not yet been implemented") + }), + BundleManagementGetSkuBundleHandler: bundle_management.GetSkuBundleHandlerFunc(func(params bundle_management.GetSkuBundleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bundle_management.GetSkuBundle has not yet been implemented") + }), + BundleManagementGetSkuBundleByNameHandler: bundle_management.GetSkuBundleByNameHandlerFunc(func(params bundle_management.GetSkuBundleByNameParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bundle_management.GetSkuBundleByName has not yet been implemented") + }), + PriceManagementGetSkuPriceHandler: price_management.GetSkuPriceHandlerFunc(func(params price_management.GetSkuPriceParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation price_management.GetSkuPrice has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + PlanManagementListCompletePlansHandler: plan_management.ListCompletePlansHandlerFunc(func(params plan_management.ListCompletePlansParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation plan_management.ListCompletePlans has not yet been implemented") + }), + CycleManagementListCyclesHandler: cycle_management.ListCyclesHandlerFunc(func(params cycle_management.ListCyclesParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation cycle_management.ListCycles has not yet been implemented") + }), + PlanManagementListPlansHandler: plan_management.ListPlansHandlerFunc(func(params plan_management.ListPlansParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation plan_management.ListPlans has not yet been implemented") + }), + BundleManagementListSkuBundlesHandler: bundle_management.ListSkuBundlesHandlerFunc(func(params bundle_management.ListSkuBundlesParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bundle_management.ListSkuBundles has not yet been implemented") + }), + PriceManagementListSkuPricesHandler: price_management.ListSkuPricesHandlerFunc(func(params price_management.ListSkuPricesParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation price_management.ListSkuPrices has not yet been implemented") + }), + SkuManagementListSkusHandler: sku_management.ListSkusHandlerFunc(func(params sku_management.ListSkusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation sku_management.ListSkus has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + CycleManagementUpdateCycleHandler: cycle_management.UpdateCycleHandlerFunc(func(params cycle_management.UpdateCycleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation cycle_management.UpdateCycle has not yet been implemented") + }), + PlanManagementUpdatePlanHandler: plan_management.UpdatePlanHandlerFunc(func(params plan_management.UpdatePlanParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation plan_management.UpdatePlan has not yet been implemented") + }), + SkuManagementUpdateSkuHandler: sku_management.UpdateSkuHandlerFunc(func(params sku_management.UpdateSkuParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation sku_management.UpdateSku has not yet been implemented") + }), + BundleManagementUpdateSkuBundleHandler: bundle_management.UpdateSkuBundleHandlerFunc(func(params bundle_management.UpdateSkuBundleParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation bundle_management.UpdateSkuBundle has not yet been implemented") + }), + PriceManagementUpdateSkuPriceHandler: price_management.UpdateSkuPriceHandlerFunc(func(params price_management.UpdateSkuPriceParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation price_management.UpdateSkuPrice has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*PlanManagerManagementAPIAPI An API which supports creation, deletion, listing etc of Plan Manager */ +type PlanManagerManagementAPIAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + useSwaggerUI bool + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // CycleManagementCreateCycleHandler sets the operation handler for the create cycle operation + CycleManagementCreateCycleHandler cycle_management.CreateCycleHandler + // PlanManagementCreatePlanHandler sets the operation handler for the create plan operation + PlanManagementCreatePlanHandler plan_management.CreatePlanHandler + // SkuManagementCreateSkuHandler sets the operation handler for the create sku operation + SkuManagementCreateSkuHandler sku_management.CreateSkuHandler + // BundleManagementCreateSkuBundleHandler sets the operation handler for the create sku bundle operation + BundleManagementCreateSkuBundleHandler bundle_management.CreateSkuBundleHandler + // PriceManagementCreateSkuPriceHandler sets the operation handler for the create sku price operation + PriceManagementCreateSkuPriceHandler price_management.CreateSkuPriceHandler + // TriggerManagementExecSampleHandler sets the operation handler for the exec sample operation + TriggerManagementExecSampleHandler trigger_management.ExecSampleHandler + // PlanManagementGetCompletePlanHandler sets the operation handler for the get complete plan operation + PlanManagementGetCompletePlanHandler plan_management.GetCompletePlanHandler + // CycleManagementGetCycleHandler sets the operation handler for the get cycle operation + CycleManagementGetCycleHandler cycle_management.GetCycleHandler + // PlanManagementGetPlanHandler sets the operation handler for the get plan operation + PlanManagementGetPlanHandler plan_management.GetPlanHandler + // SkuManagementGetSkuHandler sets the operation handler for the get sku operation + SkuManagementGetSkuHandler sku_management.GetSkuHandler + // BundleManagementGetSkuBundleHandler sets the operation handler for the get sku bundle operation + BundleManagementGetSkuBundleHandler bundle_management.GetSkuBundleHandler + // BundleManagementGetSkuBundleByNameHandler sets the operation handler for the get sku bundle by name operation + BundleManagementGetSkuBundleByNameHandler bundle_management.GetSkuBundleByNameHandler + // PriceManagementGetSkuPriceHandler sets the operation handler for the get sku price operation + PriceManagementGetSkuPriceHandler price_management.GetSkuPriceHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // PlanManagementListCompletePlansHandler sets the operation handler for the list complete plans operation + PlanManagementListCompletePlansHandler plan_management.ListCompletePlansHandler + // CycleManagementListCyclesHandler sets the operation handler for the list cycles operation + CycleManagementListCyclesHandler cycle_management.ListCyclesHandler + // PlanManagementListPlansHandler sets the operation handler for the list plans operation + PlanManagementListPlansHandler plan_management.ListPlansHandler + // BundleManagementListSkuBundlesHandler sets the operation handler for the list sku bundles operation + BundleManagementListSkuBundlesHandler bundle_management.ListSkuBundlesHandler + // PriceManagementListSkuPricesHandler sets the operation handler for the list sku prices operation + PriceManagementListSkuPricesHandler price_management.ListSkuPricesHandler + // SkuManagementListSkusHandler sets the operation handler for the list skus operation + SkuManagementListSkusHandler sku_management.ListSkusHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // CycleManagementUpdateCycleHandler sets the operation handler for the update cycle operation + CycleManagementUpdateCycleHandler cycle_management.UpdateCycleHandler + // PlanManagementUpdatePlanHandler sets the operation handler for the update plan operation + PlanManagementUpdatePlanHandler plan_management.UpdatePlanHandler + // SkuManagementUpdateSkuHandler sets the operation handler for the update sku operation + SkuManagementUpdateSkuHandler sku_management.UpdateSkuHandler + // BundleManagementUpdateSkuBundleHandler sets the operation handler for the update sku bundle operation + BundleManagementUpdateSkuBundleHandler bundle_management.UpdateSkuBundleHandler + // PriceManagementUpdateSkuPriceHandler sets the operation handler for the update sku price operation + PriceManagementUpdateSkuPriceHandler price_management.UpdateSkuPriceHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// UseRedoc for documentation at /docs +func (o *PlanManagerManagementAPIAPI) UseRedoc() { + o.useSwaggerUI = false +} + +// UseSwaggerUI for documentation at /docs +func (o *PlanManagerManagementAPIAPI) UseSwaggerUI() { + o.useSwaggerUI = true +} + +// SetDefaultProduces sets the default produces media type +func (o *PlanManagerManagementAPIAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *PlanManagerManagementAPIAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *PlanManagerManagementAPIAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *PlanManagerManagementAPIAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *PlanManagerManagementAPIAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *PlanManagerManagementAPIAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *PlanManagerManagementAPIAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the PlanManagerManagementAPIAPI +func (o *PlanManagerManagementAPIAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.CycleManagementCreateCycleHandler == nil { + unregistered = append(unregistered, "cycle_management.CreateCycleHandler") + } + if o.PlanManagementCreatePlanHandler == nil { + unregistered = append(unregistered, "plan_management.CreatePlanHandler") + } + if o.SkuManagementCreateSkuHandler == nil { + unregistered = append(unregistered, "sku_management.CreateSkuHandler") + } + if o.BundleManagementCreateSkuBundleHandler == nil { + unregistered = append(unregistered, "bundle_management.CreateSkuBundleHandler") + } + if o.PriceManagementCreateSkuPriceHandler == nil { + unregistered = append(unregistered, "price_management.CreateSkuPriceHandler") + } + if o.TriggerManagementExecSampleHandler == nil { + unregistered = append(unregistered, "trigger_management.ExecSampleHandler") + } + if o.PlanManagementGetCompletePlanHandler == nil { + unregistered = append(unregistered, "plan_management.GetCompletePlanHandler") + } + if o.CycleManagementGetCycleHandler == nil { + unregistered = append(unregistered, "cycle_management.GetCycleHandler") + } + if o.PlanManagementGetPlanHandler == nil { + unregistered = append(unregistered, "plan_management.GetPlanHandler") + } + if o.SkuManagementGetSkuHandler == nil { + unregistered = append(unregistered, "sku_management.GetSkuHandler") + } + if o.BundleManagementGetSkuBundleHandler == nil { + unregistered = append(unregistered, "bundle_management.GetSkuBundleHandler") + } + if o.BundleManagementGetSkuBundleByNameHandler == nil { + unregistered = append(unregistered, "bundle_management.GetSkuBundleByNameHandler") + } + if o.PriceManagementGetSkuPriceHandler == nil { + unregistered = append(unregistered, "price_management.GetSkuPriceHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.PlanManagementListCompletePlansHandler == nil { + unregistered = append(unregistered, "plan_management.ListCompletePlansHandler") + } + if o.CycleManagementListCyclesHandler == nil { + unregistered = append(unregistered, "cycle_management.ListCyclesHandler") + } + if o.PlanManagementListPlansHandler == nil { + unregistered = append(unregistered, "plan_management.ListPlansHandler") + } + if o.BundleManagementListSkuBundlesHandler == nil { + unregistered = append(unregistered, "bundle_management.ListSkuBundlesHandler") + } + if o.PriceManagementListSkuPricesHandler == nil { + unregistered = append(unregistered, "price_management.ListSkuPricesHandler") + } + if o.SkuManagementListSkusHandler == nil { + unregistered = append(unregistered, "sku_management.ListSkusHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + if o.CycleManagementUpdateCycleHandler == nil { + unregistered = append(unregistered, "cycle_management.UpdateCycleHandler") + } + if o.PlanManagementUpdatePlanHandler == nil { + unregistered = append(unregistered, "plan_management.UpdatePlanHandler") + } + if o.SkuManagementUpdateSkuHandler == nil { + unregistered = append(unregistered, "sku_management.UpdateSkuHandler") + } + if o.BundleManagementUpdateSkuBundleHandler == nil { + unregistered = append(unregistered, "bundle_management.UpdateSkuBundleHandler") + } + if o.PriceManagementUpdateSkuPriceHandler == nil { + unregistered = append(unregistered, "price_management.UpdateSkuPriceHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *PlanManagerManagementAPIAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *PlanManagerManagementAPIAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *PlanManagerManagementAPIAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *PlanManagerManagementAPIAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *PlanManagerManagementAPIAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *PlanManagerManagementAPIAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the plan manager management API API +func (o *PlanManagerManagementAPIAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *PlanManagerManagementAPIAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/cycle"] = cycle_management.NewCreateCycle(o.context, o.CycleManagementCreateCycleHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/plan"] = plan_management.NewCreatePlan(o.context, o.PlanManagementCreatePlanHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/sku"] = sku_management.NewCreateSku(o.context, o.SkuManagementCreateSkuHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/sku/bundle"] = bundle_management.NewCreateSkuBundle(o.context, o.BundleManagementCreateSkuBundleHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } + o.handlers["POST"]["/sku/price"] = price_management.NewCreateSkuPrice(o.context, o.PriceManagementCreateSkuPriceHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/sample"] = trigger_management.NewExecSample(o.context, o.TriggerManagementExecSampleHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/plan/complete/{id}"] = plan_management.NewGetCompletePlan(o.context, o.PlanManagementGetCompletePlanHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/cycle/{id}"] = cycle_management.NewGetCycle(o.context, o.CycleManagementGetCycleHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/plan/{id}"] = plan_management.NewGetPlan(o.context, o.PlanManagementGetPlanHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sku/{id}"] = sku_management.NewGetSku(o.context, o.SkuManagementGetSkuHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sku/bundle/{id}"] = bundle_management.NewGetSkuBundle(o.context, o.BundleManagementGetSkuBundleHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sku/bundle/name/{name}"] = bundle_management.NewGetSkuBundleByName(o.context, o.BundleManagementGetSkuBundleByNameHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sku/price/{id}"] = price_management.NewGetSkuPrice(o.context, o.PriceManagementGetSkuPriceHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/plan/complete"] = plan_management.NewListCompletePlans(o.context, o.PlanManagementListCompletePlansHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/cycle"] = cycle_management.NewListCycles(o.context, o.CycleManagementListCyclesHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/plan"] = plan_management.NewListPlans(o.context, o.PlanManagementListPlansHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sku/bundle"] = bundle_management.NewListSkuBundles(o.context, o.BundleManagementListSkuBundlesHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sku/price"] = price_management.NewListSkuPrices(o.context, o.PriceManagementListSkuPricesHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/sku"] = sku_management.NewListSkus(o.context, o.SkuManagementListSkusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/cycle/{id}"] = cycle_management.NewUpdateCycle(o.context, o.CycleManagementUpdateCycleHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/plan/{id}"] = plan_management.NewUpdatePlan(o.context, o.PlanManagementUpdatePlanHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/sku/{id}"] = sku_management.NewUpdateSku(o.context, o.SkuManagementUpdateSkuHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/sku/bundle/{id}"] = bundle_management.NewUpdateSkuBundle(o.context, o.BundleManagementUpdateSkuBundleHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } + o.handlers["PUT"]["/sku/price/{id}"] = price_management.NewUpdateSkuPrice(o.context, o.PriceManagementUpdateSkuPriceHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *PlanManagerManagementAPIAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + if o.useSwaggerUI { + return o.context.APIHandlerSwaggerUI(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *PlanManagerManagementAPIAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *PlanManagerManagementAPIAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *PlanManagerManagementAPIAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *PlanManagerManagementAPIAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/services/plan-manager/restapi/operations/price_management/create_sku_price.go b/services/plan-manager/restapi/operations/price_management/create_sku_price.go new file mode 100644 index 0000000..f55f650 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/create_sku_price.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// CreateSkuPriceHandlerFunc turns a function with the right signature into a create sku price handler +type CreateSkuPriceHandlerFunc func(CreateSkuPriceParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn CreateSkuPriceHandlerFunc) Handle(params CreateSkuPriceParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// CreateSkuPriceHandler interface for that can handle valid create sku price params +type CreateSkuPriceHandler interface { + Handle(CreateSkuPriceParams, interface{}) middleware.Responder +} + +// NewCreateSkuPrice creates a new http.Handler for the create sku price operation +func NewCreateSkuPrice(ctx *middleware.Context, handler CreateSkuPriceHandler) *CreateSkuPrice { + return &CreateSkuPrice{Context: ctx, Handler: handler} +} + +/*CreateSkuPrice swagger:route POST /sku/price priceManagement createSkuPrice + +create SKU price + +Creates a new sku price + +*/ +type CreateSkuPrice struct { + Context *middleware.Context + Handler CreateSkuPriceHandler +} + +func (o *CreateSkuPrice) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewCreateSkuPriceParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/price_management/create_sku_price_parameters.go b/services/plan-manager/restapi/operations/price_management/create_sku_price_parameters.go new file mode 100644 index 0000000..fa28246 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/create_sku_price_parameters.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateSkuPriceParams creates a new CreateSkuPriceParams object +// no default values defined in spec. +func NewCreateSkuPriceParams() CreateSkuPriceParams { + + return CreateSkuPriceParams{} +} + +// CreateSkuPriceParams contains all the bound params for the create sku price operation +// typically these are obtained from a http.Request +// +// swagger:parameters createSkuPrice +type CreateSkuPriceParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*SKU price to be added + In: body + */ + Price *models.SkuPrice +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewCreateSkuPriceParams() beforehand. +func (o *CreateSkuPriceParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.SkuPrice + if err := route.Consumer.Consume(r.Body, &body); err != nil { + res = append(res, errors.NewParseError("price", "body", "", err)) + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Price = &body + } + } + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/price_management/create_sku_price_responses.go b/services/plan-manager/restapi/operations/price_management/create_sku_price_responses.go new file mode 100644 index 0000000..42624d8 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/create_sku_price_responses.go @@ -0,0 +1,170 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateSkuPriceCreatedCode is the HTTP code returned for type CreateSkuPriceCreated +const CreateSkuPriceCreatedCode int = 201 + +/*CreateSkuPriceCreated item created + +swagger:response createSkuPriceCreated +*/ +type CreateSkuPriceCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewCreateSkuPriceCreated creates CreateSkuPriceCreated with default headers values +func NewCreateSkuPriceCreated() *CreateSkuPriceCreated { + + return &CreateSkuPriceCreated{} +} + +// WithPayload adds the payload to the create sku price created response +func (o *CreateSkuPriceCreated) WithPayload(payload *models.ItemCreatedResponse) *CreateSkuPriceCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku price created response +func (o *CreateSkuPriceCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuPriceCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateSkuPriceBadRequestCode is the HTTP code returned for type CreateSkuPriceBadRequest +const CreateSkuPriceBadRequestCode int = 400 + +/*CreateSkuPriceBadRequest invalid input, object invalid + +swagger:response createSkuPriceBadRequest +*/ +type CreateSkuPriceBadRequest struct { +} + +// NewCreateSkuPriceBadRequest creates CreateSkuPriceBadRequest with default headers values +func NewCreateSkuPriceBadRequest() *CreateSkuPriceBadRequest { + + return &CreateSkuPriceBadRequest{} +} + +// WriteResponse to the client +func (o *CreateSkuPriceBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// CreateSkuPriceConflictCode is the HTTP code returned for type CreateSkuPriceConflict +const CreateSkuPriceConflictCode int = 409 + +/*CreateSkuPriceConflict an existing item already exists + +swagger:response createSkuPriceConflict +*/ +type CreateSkuPriceConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateSkuPriceConflict creates CreateSkuPriceConflict with default headers values +func NewCreateSkuPriceConflict() *CreateSkuPriceConflict { + + return &CreateSkuPriceConflict{} +} + +// WithPayload adds the payload to the create sku price conflict response +func (o *CreateSkuPriceConflict) WithPayload(payload *models.ErrorResponse) *CreateSkuPriceConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku price conflict response +func (o *CreateSkuPriceConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuPriceConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateSkuPriceInternalServerErrorCode is the HTTP code returned for type CreateSkuPriceInternalServerError +const CreateSkuPriceInternalServerErrorCode int = 500 + +/*CreateSkuPriceInternalServerError unexpected error + +swagger:response createSkuPriceInternalServerError +*/ +type CreateSkuPriceInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateSkuPriceInternalServerError creates CreateSkuPriceInternalServerError with default headers values +func NewCreateSkuPriceInternalServerError() *CreateSkuPriceInternalServerError { + + return &CreateSkuPriceInternalServerError{} +} + +// WithPayload adds the payload to the create sku price internal server error response +func (o *CreateSkuPriceInternalServerError) WithPayload(payload *models.ErrorResponse) *CreateSkuPriceInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku price internal server error response +func (o *CreateSkuPriceInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuPriceInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/price_management/create_sku_price_urlbuilder.go b/services/plan-manager/restapi/operations/price_management/create_sku_price_urlbuilder.go new file mode 100644 index 0000000..6ab0cde --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/create_sku_price_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// CreateSkuPriceURL generates an URL for the create sku price operation +type CreateSkuPriceURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateSkuPriceURL) WithBasePath(bp string) *CreateSkuPriceURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateSkuPriceURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *CreateSkuPriceURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/price" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *CreateSkuPriceURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *CreateSkuPriceURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *CreateSkuPriceURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on CreateSkuPriceURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on CreateSkuPriceURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *CreateSkuPriceURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/price_management/get_sku_price.go b/services/plan-manager/restapi/operations/price_management/get_sku_price.go new file mode 100644 index 0000000..ad2fd0d --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/get_sku_price.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetSkuPriceHandlerFunc turns a function with the right signature into a get sku price handler +type GetSkuPriceHandlerFunc func(GetSkuPriceParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetSkuPriceHandlerFunc) Handle(params GetSkuPriceParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetSkuPriceHandler interface for that can handle valid get sku price params +type GetSkuPriceHandler interface { + Handle(GetSkuPriceParams, interface{}) middleware.Responder +} + +// NewGetSkuPrice creates a new http.Handler for the get sku price operation +func NewGetSkuPrice(ctx *middleware.Context, handler GetSkuPriceHandler) *GetSkuPrice { + return &GetSkuPrice{Context: ctx, Handler: handler} +} + +/*GetSkuPrice swagger:route GET /sku/price/{id} priceManagement getSkuPrice + +Get specific sku price + +get sku price with given skupriceid + +*/ +type GetSkuPrice struct { + Context *middleware.Context + Handler GetSkuPriceHandler +} + +func (o *GetSkuPrice) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetSkuPriceParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/price_management/get_sku_price_parameters.go b/services/plan-manager/restapi/operations/price_management/get_sku_price_parameters.go new file mode 100644 index 0000000..073aa7b --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/get_sku_price_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuPriceParams creates a new GetSkuPriceParams object +// no default values defined in spec. +func NewGetSkuPriceParams() GetSkuPriceParams { + + return GetSkuPriceParams{} +} + +// GetSkuPriceParams contains all the bound params for the get sku price operation +// typically these are obtained from a http.Request +// +// swagger:parameters getSkuPrice +type GetSkuPriceParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of sku price to be obtained + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetSkuPriceParams() beforehand. +func (o *GetSkuPriceParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetSkuPriceParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/price_management/get_sku_price_responses.go b/services/plan-manager/restapi/operations/price_management/get_sku_price_responses.go new file mode 100644 index 0000000..6d167d2 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/get_sku_price_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuPriceOKCode is the HTTP code returned for type GetSkuPriceOK +const GetSkuPriceOKCode int = 200 + +/*GetSkuPriceOK sku price returned + +swagger:response getSkuPriceOK +*/ +type GetSkuPriceOK struct { + + /* + In: Body + */ + Payload *models.SkuPrice `json:"body,omitempty"` +} + +// NewGetSkuPriceOK creates GetSkuPriceOK with default headers values +func NewGetSkuPriceOK() *GetSkuPriceOK { + + return &GetSkuPriceOK{} +} + +// WithPayload adds the payload to the get sku price o k response +func (o *GetSkuPriceOK) WithPayload(payload *models.SkuPrice) *GetSkuPriceOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku price o k response +func (o *GetSkuPriceOK) SetPayload(payload *models.SkuPrice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuPriceOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuPriceNotFoundCode is the HTTP code returned for type GetSkuPriceNotFound +const GetSkuPriceNotFoundCode int = 404 + +/*GetSkuPriceNotFound sku price with skupriceid not found + +swagger:response getSkuPriceNotFound +*/ +type GetSkuPriceNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuPriceNotFound creates GetSkuPriceNotFound with default headers values +func NewGetSkuPriceNotFound() *GetSkuPriceNotFound { + + return &GetSkuPriceNotFound{} +} + +// WithPayload adds the payload to the get sku price not found response +func (o *GetSkuPriceNotFound) WithPayload(payload *models.ErrorResponse) *GetSkuPriceNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku price not found response +func (o *GetSkuPriceNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuPriceNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuPriceInternalServerErrorCode is the HTTP code returned for type GetSkuPriceInternalServerError +const GetSkuPriceInternalServerErrorCode int = 500 + +/*GetSkuPriceInternalServerError unexpected error + +swagger:response getSkuPriceInternalServerError +*/ +type GetSkuPriceInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuPriceInternalServerError creates GetSkuPriceInternalServerError with default headers values +func NewGetSkuPriceInternalServerError() *GetSkuPriceInternalServerError { + + return &GetSkuPriceInternalServerError{} +} + +// WithPayload adds the payload to the get sku price internal server error response +func (o *GetSkuPriceInternalServerError) WithPayload(payload *models.ErrorResponse) *GetSkuPriceInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku price internal server error response +func (o *GetSkuPriceInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuPriceInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/price_management/get_sku_price_urlbuilder.go b/services/plan-manager/restapi/operations/price_management/get_sku_price_urlbuilder.go new file mode 100644 index 0000000..97232b9 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/get_sku_price_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetSkuPriceURL generates an URL for the get sku price operation +type GetSkuPriceURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuPriceURL) WithBasePath(bp string) *GetSkuPriceURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuPriceURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetSkuPriceURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/price/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetSkuPriceURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetSkuPriceURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetSkuPriceURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetSkuPriceURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetSkuPriceURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetSkuPriceURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetSkuPriceURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/price_management/list_sku_prices.go b/services/plan-manager/restapi/operations/price_management/list_sku_prices.go new file mode 100644 index 0000000..3b327ea --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/list_sku_prices.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListSkuPricesHandlerFunc turns a function with the right signature into a list sku prices handler +type ListSkuPricesHandlerFunc func(ListSkuPricesParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListSkuPricesHandlerFunc) Handle(params ListSkuPricesParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListSkuPricesHandler interface for that can handle valid list sku prices params +type ListSkuPricesHandler interface { + Handle(ListSkuPricesParams, interface{}) middleware.Responder +} + +// NewListSkuPrices creates a new http.Handler for the list sku prices operation +func NewListSkuPrices(ctx *middleware.Context, handler ListSkuPricesHandler) *ListSkuPrices { + return &ListSkuPrices{Context: ctx, Handler: handler} +} + +/*ListSkuPrices swagger:route GET /sku/price priceManagement listSkuPrices + +list SKU Prices + +lists all sku prices + +*/ +type ListSkuPrices struct { + Context *middleware.Context + Handler ListSkuPricesHandler +} + +func (o *ListSkuPrices) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListSkuPricesParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/price_management/list_sku_prices_parameters.go b/services/plan-manager/restapi/operations/price_management/list_sku_prices_parameters.go new file mode 100644 index 0000000..01dc6b7 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/list_sku_prices_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListSkuPricesParams creates a new ListSkuPricesParams object +// no default values defined in spec. +func NewListSkuPricesParams() ListSkuPricesParams { + + return ListSkuPricesParams{} +} + +// ListSkuPricesParams contains all the bound params for the list sku prices operation +// typically these are obtained from a http.Request +// +// swagger:parameters listSkuPrices +type ListSkuPricesParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListSkuPricesParams() beforehand. +func (o *ListSkuPricesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/price_management/list_sku_prices_responses.go b/services/plan-manager/restapi/operations/price_management/list_sku_prices_responses.go new file mode 100644 index 0000000..1cff436 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/list_sku_prices_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListSkuPricesOKCode is the HTTP code returned for type ListSkuPricesOK +const ListSkuPricesOKCode int = 200 + +/*ListSkuPricesOK list of skus prices returned + +swagger:response listSkuPricesOK +*/ +type ListSkuPricesOK struct { + + /* + In: Body + */ + Payload []*models.SkuPrice `json:"body,omitempty"` +} + +// NewListSkuPricesOK creates ListSkuPricesOK with default headers values +func NewListSkuPricesOK() *ListSkuPricesOK { + + return &ListSkuPricesOK{} +} + +// WithPayload adds the payload to the list sku prices o k response +func (o *ListSkuPricesOK) WithPayload(payload []*models.SkuPrice) *ListSkuPricesOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list sku prices o k response +func (o *ListSkuPricesOK) SetPayload(payload []*models.SkuPrice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListSkuPricesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.SkuPrice, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListSkuPricesInternalServerErrorCode is the HTTP code returned for type ListSkuPricesInternalServerError +const ListSkuPricesInternalServerErrorCode int = 500 + +/*ListSkuPricesInternalServerError unexpected error + +swagger:response listSkuPricesInternalServerError +*/ +type ListSkuPricesInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListSkuPricesInternalServerError creates ListSkuPricesInternalServerError with default headers values +func NewListSkuPricesInternalServerError() *ListSkuPricesInternalServerError { + + return &ListSkuPricesInternalServerError{} +} + +// WithPayload adds the payload to the list sku prices internal server error response +func (o *ListSkuPricesInternalServerError) WithPayload(payload *models.ErrorResponse) *ListSkuPricesInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list sku prices internal server error response +func (o *ListSkuPricesInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListSkuPricesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/price_management/list_sku_prices_urlbuilder.go b/services/plan-manager/restapi/operations/price_management/list_sku_prices_urlbuilder.go new file mode 100644 index 0000000..6cdea5e --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/list_sku_prices_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListSkuPricesURL generates an URL for the list sku prices operation +type ListSkuPricesURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListSkuPricesURL) WithBasePath(bp string) *ListSkuPricesURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListSkuPricesURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListSkuPricesURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/price" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListSkuPricesURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListSkuPricesURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListSkuPricesURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListSkuPricesURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListSkuPricesURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListSkuPricesURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/price_management/update_sku_price.go b/services/plan-manager/restapi/operations/price_management/update_sku_price.go new file mode 100644 index 0000000..98da428 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/update_sku_price.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdateSkuPriceHandlerFunc turns a function with the right signature into a update sku price handler +type UpdateSkuPriceHandlerFunc func(UpdateSkuPriceParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateSkuPriceHandlerFunc) Handle(params UpdateSkuPriceParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdateSkuPriceHandler interface for that can handle valid update sku price params +type UpdateSkuPriceHandler interface { + Handle(UpdateSkuPriceParams, interface{}) middleware.Responder +} + +// NewUpdateSkuPrice creates a new http.Handler for the update sku price operation +func NewUpdateSkuPrice(ctx *middleware.Context, handler UpdateSkuPriceHandler) *UpdateSkuPrice { + return &UpdateSkuPrice{Context: ctx, Handler: handler} +} + +/*UpdateSkuPrice swagger:route PUT /sku/price/{id} priceManagement updateSkuPrice + +Update specific sku price + +Update sku price with given skupriceid + +*/ +type UpdateSkuPrice struct { + Context *middleware.Context + Handler UpdateSkuPriceHandler +} + +func (o *UpdateSkuPrice) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateSkuPriceParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/price_management/update_sku_price_parameters.go b/services/plan-manager/restapi/operations/price_management/update_sku_price_parameters.go new file mode 100644 index 0000000..58aaa56 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/update_sku_price_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateSkuPriceParams creates a new UpdateSkuPriceParams object +// no default values defined in spec. +func NewUpdateSkuPriceParams() UpdateSkuPriceParams { + + return UpdateSkuPriceParams{} +} + +// UpdateSkuPriceParams contains all the bound params for the update sku price operation +// typically these are obtained from a http.Request +// +// swagger:parameters updateSkuPrice +type UpdateSkuPriceParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of sku price to be obtained + Required: true + In: path + */ + ID string + /*updated sku containing all parameters except id + Required: true + In: body + */ + Price *models.SkuPrice +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateSkuPriceParams() beforehand. +func (o *UpdateSkuPriceParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.SkuPrice + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("price", "body", "")) + } else { + res = append(res, errors.NewParseError("price", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Price = &body + } + } + } else { + res = append(res, errors.Required("price", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdateSkuPriceParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/price_management/update_sku_price_responses.go b/services/plan-manager/restapi/operations/price_management/update_sku_price_responses.go new file mode 100644 index 0000000..2fe55bf --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/update_sku_price_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateSkuPriceOKCode is the HTTP code returned for type UpdateSkuPriceOK +const UpdateSkuPriceOKCode int = 200 + +/*UpdateSkuPriceOK updated sku price + +swagger:response updateSkuPriceOK +*/ +type UpdateSkuPriceOK struct { + + /* + In: Body + */ + Payload *models.SkuPrice `json:"body,omitempty"` +} + +// NewUpdateSkuPriceOK creates UpdateSkuPriceOK with default headers values +func NewUpdateSkuPriceOK() *UpdateSkuPriceOK { + + return &UpdateSkuPriceOK{} +} + +// WithPayload adds the payload to the update sku price o k response +func (o *UpdateSkuPriceOK) WithPayload(payload *models.SkuPrice) *UpdateSkuPriceOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku price o k response +func (o *UpdateSkuPriceOK) SetPayload(payload *models.SkuPrice) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuPriceOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateSkuPriceNotFoundCode is the HTTP code returned for type UpdateSkuPriceNotFound +const UpdateSkuPriceNotFoundCode int = 404 + +/*UpdateSkuPriceNotFound sku price with skupriceid not found + +swagger:response updateSkuPriceNotFound +*/ +type UpdateSkuPriceNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateSkuPriceNotFound creates UpdateSkuPriceNotFound with default headers values +func NewUpdateSkuPriceNotFound() *UpdateSkuPriceNotFound { + + return &UpdateSkuPriceNotFound{} +} + +// WithPayload adds the payload to the update sku price not found response +func (o *UpdateSkuPriceNotFound) WithPayload(payload *models.ErrorResponse) *UpdateSkuPriceNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku price not found response +func (o *UpdateSkuPriceNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuPriceNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateSkuPriceInternalServerErrorCode is the HTTP code returned for type UpdateSkuPriceInternalServerError +const UpdateSkuPriceInternalServerErrorCode int = 500 + +/*UpdateSkuPriceInternalServerError unexpected error + +swagger:response updateSkuPriceInternalServerError +*/ +type UpdateSkuPriceInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateSkuPriceInternalServerError creates UpdateSkuPriceInternalServerError with default headers values +func NewUpdateSkuPriceInternalServerError() *UpdateSkuPriceInternalServerError { + + return &UpdateSkuPriceInternalServerError{} +} + +// WithPayload adds the payload to the update sku price internal server error response +func (o *UpdateSkuPriceInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdateSkuPriceInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku price internal server error response +func (o *UpdateSkuPriceInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuPriceInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/price_management/update_sku_price_urlbuilder.go b/services/plan-manager/restapi/operations/price_management/update_sku_price_urlbuilder.go new file mode 100644 index 0000000..fb52510 --- /dev/null +++ b/services/plan-manager/restapi/operations/price_management/update_sku_price_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package price_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdateSkuPriceURL generates an URL for the update sku price operation +type UpdateSkuPriceURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateSkuPriceURL) WithBasePath(bp string) *UpdateSkuPriceURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateSkuPriceURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateSkuPriceURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/price/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdateSkuPriceURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateSkuPriceURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateSkuPriceURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateSkuPriceURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateSkuPriceURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateSkuPriceURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateSkuPriceURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/sku_management/create_sku.go b/services/plan-manager/restapi/operations/sku_management/create_sku.go new file mode 100644 index 0000000..0c20424 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/create_sku.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// CreateSkuHandlerFunc turns a function with the right signature into a create sku handler +type CreateSkuHandlerFunc func(CreateSkuParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn CreateSkuHandlerFunc) Handle(params CreateSkuParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// CreateSkuHandler interface for that can handle valid create sku params +type CreateSkuHandler interface { + Handle(CreateSkuParams, interface{}) middleware.Responder +} + +// NewCreateSku creates a new http.Handler for the create sku operation +func NewCreateSku(ctx *middleware.Context, handler CreateSkuHandler) *CreateSku { + return &CreateSku{Context: ctx, Handler: handler} +} + +/*CreateSku swagger:route POST /sku skuManagement createSku + +create SKU + +Creates a new sku + +*/ +type CreateSku struct { + Context *middleware.Context + Handler CreateSkuHandler +} + +func (o *CreateSku) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewCreateSkuParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/sku_management/create_sku_parameters.go b/services/plan-manager/restapi/operations/sku_management/create_sku_parameters.go new file mode 100644 index 0000000..227f541 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/create_sku_parameters.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewCreateSkuParams creates a new CreateSkuParams object +// no default values defined in spec. +func NewCreateSkuParams() CreateSkuParams { + + return CreateSkuParams{} +} + +// CreateSkuParams contains all the bound params for the create sku operation +// typically these are obtained from a http.Request +// +// swagger:parameters createSku +type CreateSkuParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*SKU to be added + In: body + */ + Sku *models.Sku +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewCreateSkuParams() beforehand. +func (o *CreateSkuParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Sku + if err := route.Consumer.Consume(r.Body, &body); err != nil { + res = append(res, errors.NewParseError("sku", "body", "", err)) + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Sku = &body + } + } + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/sku_management/create_sku_responses.go b/services/plan-manager/restapi/operations/sku_management/create_sku_responses.go new file mode 100644 index 0000000..a8e2447 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/create_sku_responses.go @@ -0,0 +1,170 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// CreateSkuCreatedCode is the HTTP code returned for type CreateSkuCreated +const CreateSkuCreatedCode int = 201 + +/*CreateSkuCreated item created + +swagger:response createSkuCreated +*/ +type CreateSkuCreated struct { + + /* + In: Body + */ + Payload *models.ItemCreatedResponse `json:"body,omitempty"` +} + +// NewCreateSkuCreated creates CreateSkuCreated with default headers values +func NewCreateSkuCreated() *CreateSkuCreated { + + return &CreateSkuCreated{} +} + +// WithPayload adds the payload to the create sku created response +func (o *CreateSkuCreated) WithPayload(payload *models.ItemCreatedResponse) *CreateSkuCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku created response +func (o *CreateSkuCreated) SetPayload(payload *models.ItemCreatedResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(201) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateSkuBadRequestCode is the HTTP code returned for type CreateSkuBadRequest +const CreateSkuBadRequestCode int = 400 + +/*CreateSkuBadRequest invalid input, object invalid + +swagger:response createSkuBadRequest +*/ +type CreateSkuBadRequest struct { +} + +// NewCreateSkuBadRequest creates CreateSkuBadRequest with default headers values +func NewCreateSkuBadRequest() *CreateSkuBadRequest { + + return &CreateSkuBadRequest{} +} + +// WriteResponse to the client +func (o *CreateSkuBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(400) +} + +// CreateSkuConflictCode is the HTTP code returned for type CreateSkuConflict +const CreateSkuConflictCode int = 409 + +/*CreateSkuConflict an existing item already exists + +swagger:response createSkuConflict +*/ +type CreateSkuConflict struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateSkuConflict creates CreateSkuConflict with default headers values +func NewCreateSkuConflict() *CreateSkuConflict { + + return &CreateSkuConflict{} +} + +// WithPayload adds the payload to the create sku conflict response +func (o *CreateSkuConflict) WithPayload(payload *models.ErrorResponse) *CreateSkuConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku conflict response +func (o *CreateSkuConflict) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(409) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// CreateSkuInternalServerErrorCode is the HTTP code returned for type CreateSkuInternalServerError +const CreateSkuInternalServerErrorCode int = 500 + +/*CreateSkuInternalServerError unexpected error + +swagger:response createSkuInternalServerError +*/ +type CreateSkuInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewCreateSkuInternalServerError creates CreateSkuInternalServerError with default headers values +func NewCreateSkuInternalServerError() *CreateSkuInternalServerError { + + return &CreateSkuInternalServerError{} +} + +// WithPayload adds the payload to the create sku internal server error response +func (o *CreateSkuInternalServerError) WithPayload(payload *models.ErrorResponse) *CreateSkuInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create sku internal server error response +func (o *CreateSkuInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateSkuInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/sku_management/create_sku_urlbuilder.go b/services/plan-manager/restapi/operations/sku_management/create_sku_urlbuilder.go new file mode 100644 index 0000000..cd58c9f --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/create_sku_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// CreateSkuURL generates an URL for the create sku operation +type CreateSkuURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateSkuURL) WithBasePath(bp string) *CreateSkuURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *CreateSkuURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *CreateSkuURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *CreateSkuURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *CreateSkuURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *CreateSkuURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on CreateSkuURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on CreateSkuURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *CreateSkuURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/sku_management/get_sku.go b/services/plan-manager/restapi/operations/sku_management/get_sku.go new file mode 100644 index 0000000..6bfd560 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/get_sku.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetSkuHandlerFunc turns a function with the right signature into a get sku handler +type GetSkuHandlerFunc func(GetSkuParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetSkuHandlerFunc) Handle(params GetSkuParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetSkuHandler interface for that can handle valid get sku params +type GetSkuHandler interface { + Handle(GetSkuParams, interface{}) middleware.Responder +} + +// NewGetSku creates a new http.Handler for the get sku operation +func NewGetSku(ctx *middleware.Context, handler GetSkuHandler) *GetSku { + return &GetSku{Context: ctx, Handler: handler} +} + +/*GetSku swagger:route GET /sku/{id} skuManagement getSku + +Get specific sku + +get sku with given skuid + +*/ +type GetSku struct { + Context *middleware.Context + Handler GetSkuHandler +} + +func (o *GetSku) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetSkuParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/sku_management/get_sku_parameters.go b/services/plan-manager/restapi/operations/sku_management/get_sku_parameters.go new file mode 100644 index 0000000..d6242d1 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/get_sku_parameters.go @@ -0,0 +1,72 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" +) + +// NewGetSkuParams creates a new GetSkuParams object +// no default values defined in spec. +func NewGetSkuParams() GetSkuParams { + + return GetSkuParams{} +} + +// GetSkuParams contains all the bound params for the get sku operation +// typically these are obtained from a http.Request +// +// swagger:parameters getSku +type GetSkuParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of sku to be obtained + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetSkuParams() beforehand. +func (o *GetSkuParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetSkuParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/sku_management/get_sku_responses.go b/services/plan-manager/restapi/operations/sku_management/get_sku_responses.go new file mode 100644 index 0000000..db31564 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/get_sku_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetSkuOKCode is the HTTP code returned for type GetSkuOK +const GetSkuOKCode int = 200 + +/*GetSkuOK sku returned + +swagger:response getSkuOK +*/ +type GetSkuOK struct { + + /* + In: Body + */ + Payload *models.Sku `json:"body,omitempty"` +} + +// NewGetSkuOK creates GetSkuOK with default headers values +func NewGetSkuOK() *GetSkuOK { + + return &GetSkuOK{} +} + +// WithPayload adds the payload to the get sku o k response +func (o *GetSkuOK) WithPayload(payload *models.Sku) *GetSkuOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku o k response +func (o *GetSkuOK) SetPayload(payload *models.Sku) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuNotFoundCode is the HTTP code returned for type GetSkuNotFound +const GetSkuNotFoundCode int = 404 + +/*GetSkuNotFound sku with skuid not found + +swagger:response getSkuNotFound +*/ +type GetSkuNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuNotFound creates GetSkuNotFound with default headers values +func NewGetSkuNotFound() *GetSkuNotFound { + + return &GetSkuNotFound{} +} + +// WithPayload adds the payload to the get sku not found response +func (o *GetSkuNotFound) WithPayload(payload *models.ErrorResponse) *GetSkuNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku not found response +func (o *GetSkuNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetSkuInternalServerErrorCode is the HTTP code returned for type GetSkuInternalServerError +const GetSkuInternalServerErrorCode int = 500 + +/*GetSkuInternalServerError unexpected error + +swagger:response getSkuInternalServerError +*/ +type GetSkuInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSkuInternalServerError creates GetSkuInternalServerError with default headers values +func NewGetSkuInternalServerError() *GetSkuInternalServerError { + + return &GetSkuInternalServerError{} +} + +// WithPayload adds the payload to the get sku internal server error response +func (o *GetSkuInternalServerError) WithPayload(payload *models.ErrorResponse) *GetSkuInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get sku internal server error response +func (o *GetSkuInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSkuInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/sku_management/get_sku_urlbuilder.go b/services/plan-manager/restapi/operations/sku_management/get_sku_urlbuilder.go new file mode 100644 index 0000000..8fec806 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/get_sku_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetSkuURL generates an URL for the get sku operation +type GetSkuURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuURL) WithBasePath(bp string) *GetSkuURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSkuURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetSkuURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetSkuURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetSkuURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetSkuURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetSkuURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetSkuURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetSkuURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetSkuURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/sku_management/list_skus.go b/services/plan-manager/restapi/operations/sku_management/list_skus.go new file mode 100644 index 0000000..f1edaa0 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/list_skus.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ListSkusHandlerFunc turns a function with the right signature into a list skus handler +type ListSkusHandlerFunc func(ListSkusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ListSkusHandlerFunc) Handle(params ListSkusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ListSkusHandler interface for that can handle valid list skus params +type ListSkusHandler interface { + Handle(ListSkusParams, interface{}) middleware.Responder +} + +// NewListSkus creates a new http.Handler for the list skus operation +func NewListSkus(ctx *middleware.Context, handler ListSkusHandler) *ListSkus { + return &ListSkus{Context: ctx, Handler: handler} +} + +/*ListSkus swagger:route GET /sku skuManagement listSkus + +list SKUs + +lists all skus + +*/ +type ListSkus struct { + Context *middleware.Context + Handler ListSkusHandler +} + +func (o *ListSkus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewListSkusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/sku_management/list_skus_parameters.go b/services/plan-manager/restapi/operations/sku_management/list_skus_parameters.go new file mode 100644 index 0000000..af3e16a --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/list_skus_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewListSkusParams creates a new ListSkusParams object +// no default values defined in spec. +func NewListSkusParams() ListSkusParams { + + return ListSkusParams{} +} + +// ListSkusParams contains all the bound params for the list skus operation +// typically these are obtained from a http.Request +// +// swagger:parameters listSkus +type ListSkusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewListSkusParams() beforehand. +func (o *ListSkusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/sku_management/list_skus_responses.go b/services/plan-manager/restapi/operations/sku_management/list_skus_responses.go new file mode 100644 index 0000000..10f0b60 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/list_skus_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ListSkusOKCode is the HTTP code returned for type ListSkusOK +const ListSkusOKCode int = 200 + +/*ListSkusOK list of skus returned + +swagger:response listSkusOK +*/ +type ListSkusOK struct { + + /* + In: Body + */ + Payload []*models.Sku `json:"body,omitempty"` +} + +// NewListSkusOK creates ListSkusOK with default headers values +func NewListSkusOK() *ListSkusOK { + + return &ListSkusOK{} +} + +// WithPayload adds the payload to the list skus o k response +func (o *ListSkusOK) WithPayload(payload []*models.Sku) *ListSkusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list skus o k response +func (o *ListSkusOK) SetPayload(payload []*models.Sku) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListSkusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Sku, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// ListSkusInternalServerErrorCode is the HTTP code returned for type ListSkusInternalServerError +const ListSkusInternalServerErrorCode int = 500 + +/*ListSkusInternalServerError unexpected error + +swagger:response listSkusInternalServerError +*/ +type ListSkusInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewListSkusInternalServerError creates ListSkusInternalServerError with default headers values +func NewListSkusInternalServerError() *ListSkusInternalServerError { + + return &ListSkusInternalServerError{} +} + +// WithPayload adds the payload to the list skus internal server error response +func (o *ListSkusInternalServerError) WithPayload(payload *models.ErrorResponse) *ListSkusInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the list skus internal server error response +func (o *ListSkusInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ListSkusInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/sku_management/list_skus_urlbuilder.go b/services/plan-manager/restapi/operations/sku_management/list_skus_urlbuilder.go new file mode 100644 index 0000000..461db9a --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/list_skus_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ListSkusURL generates an URL for the list skus operation +type ListSkusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListSkusURL) WithBasePath(bp string) *ListSkusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ListSkusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ListSkusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ListSkusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ListSkusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ListSkusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ListSkusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ListSkusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ListSkusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/sku_management/update_sku.go b/services/plan-manager/restapi/operations/sku_management/update_sku.go new file mode 100644 index 0000000..e3b4017 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/update_sku.go @@ -0,0 +1,73 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// UpdateSkuHandlerFunc turns a function with the right signature into a update sku handler +type UpdateSkuHandlerFunc func(UpdateSkuParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn UpdateSkuHandlerFunc) Handle(params UpdateSkuParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// UpdateSkuHandler interface for that can handle valid update sku params +type UpdateSkuHandler interface { + Handle(UpdateSkuParams, interface{}) middleware.Responder +} + +// NewUpdateSku creates a new http.Handler for the update sku operation +func NewUpdateSku(ctx *middleware.Context, handler UpdateSkuHandler) *UpdateSku { + return &UpdateSku{Context: ctx, Handler: handler} +} + +/*UpdateSku swagger:route PUT /sku/{id} skuManagement updateSku + +Update specific sku + +Update sku with given skuid + +*/ +type UpdateSku struct { + Context *middleware.Context + Handler UpdateSkuHandler +} + +func (o *UpdateSku) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewUpdateSkuParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/sku_management/update_sku_parameters.go b/services/plan-manager/restapi/operations/sku_management/update_sku_parameters.go new file mode 100644 index 0000000..c967b45 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/update_sku_parameters.go @@ -0,0 +1,103 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "io" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// NewUpdateSkuParams creates a new UpdateSkuParams object +// no default values defined in spec. +func NewUpdateSkuParams() UpdateSkuParams { + + return UpdateSkuParams{} +} + +// UpdateSkuParams contains all the bound params for the update sku operation +// typically these are obtained from a http.Request +// +// swagger:parameters updateSku +type UpdateSkuParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of sku to be obtained + Required: true + In: path + */ + ID string + /*updated sku containing all parameters except id + Required: true + In: body + */ + Sku *models.Sku +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewUpdateSkuParams() beforehand. +func (o *UpdateSkuParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if runtime.HasBody(r) { + defer r.Body.Close() + var body models.Sku + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("sku", "body", "")) + } else { + res = append(res, errors.NewParseError("sku", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Sku = &body + } + } + } else { + res = append(res, errors.Required("sku", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *UpdateSkuParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} diff --git a/services/plan-manager/restapi/operations/sku_management/update_sku_responses.go b/services/plan-manager/restapi/operations/sku_management/update_sku_responses.go new file mode 100644 index 0000000..e3deb61 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/update_sku_responses.go @@ -0,0 +1,146 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// UpdateSkuOKCode is the HTTP code returned for type UpdateSkuOK +const UpdateSkuOKCode int = 200 + +/*UpdateSkuOK updated sku + +swagger:response updateSkuOK +*/ +type UpdateSkuOK struct { + + /* + In: Body + */ + Payload *models.Sku `json:"body,omitempty"` +} + +// NewUpdateSkuOK creates UpdateSkuOK with default headers values +func NewUpdateSkuOK() *UpdateSkuOK { + + return &UpdateSkuOK{} +} + +// WithPayload adds the payload to the update sku o k response +func (o *UpdateSkuOK) WithPayload(payload *models.Sku) *UpdateSkuOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku o k response +func (o *UpdateSkuOK) SetPayload(payload *models.Sku) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateSkuNotFoundCode is the HTTP code returned for type UpdateSkuNotFound +const UpdateSkuNotFoundCode int = 404 + +/*UpdateSkuNotFound sku with skuid not found + +swagger:response updateSkuNotFound +*/ +type UpdateSkuNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateSkuNotFound creates UpdateSkuNotFound with default headers values +func NewUpdateSkuNotFound() *UpdateSkuNotFound { + + return &UpdateSkuNotFound{} +} + +// WithPayload adds the payload to the update sku not found response +func (o *UpdateSkuNotFound) WithPayload(payload *models.ErrorResponse) *UpdateSkuNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku not found response +func (o *UpdateSkuNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// UpdateSkuInternalServerErrorCode is the HTTP code returned for type UpdateSkuInternalServerError +const UpdateSkuInternalServerErrorCode int = 500 + +/*UpdateSkuInternalServerError unexpected error + +swagger:response updateSkuInternalServerError +*/ +type UpdateSkuInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewUpdateSkuInternalServerError creates UpdateSkuInternalServerError with default headers values +func NewUpdateSkuInternalServerError() *UpdateSkuInternalServerError { + + return &UpdateSkuInternalServerError{} +} + +// WithPayload adds the payload to the update sku internal server error response +func (o *UpdateSkuInternalServerError) WithPayload(payload *models.ErrorResponse) *UpdateSkuInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the update sku internal server error response +func (o *UpdateSkuInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *UpdateSkuInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/sku_management/update_sku_urlbuilder.go b/services/plan-manager/restapi/operations/sku_management/update_sku_urlbuilder.go new file mode 100644 index 0000000..2229a82 --- /dev/null +++ b/services/plan-manager/restapi/operations/sku_management/update_sku_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package sku_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// UpdateSkuURL generates an URL for the update sku operation +type UpdateSkuURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateSkuURL) WithBasePath(bp string) *UpdateSkuURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *UpdateSkuURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *UpdateSkuURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/sku/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on UpdateSkuURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *UpdateSkuURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *UpdateSkuURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *UpdateSkuURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on UpdateSkuURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on UpdateSkuURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *UpdateSkuURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/status_management/get_status.go b/services/plan-manager/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/status_management/get_status_parameters.go b/services/plan-manager/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..2b53fa8 --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the endpoint to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"kafka-receiver", "kafka-sender", "status", "trigger", "bundle", "cycle", "plan", "price", "sku"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/plan-manager/restapi/operations/status_management/get_status_responses.go b/services/plan-manager/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..f944f3a --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/status_management/get_status_urlbuilder.go b/services/plan-manager/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..151ece5 --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/status_management/show_status.go b/services/plan-manager/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/status_management/show_status_parameters.go b/services/plan-manager/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/status_management/show_status_responses.go b/services/plan-manager/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..fc8d6db --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/status_management/show_status_urlbuilder.go b/services/plan-manager/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..6efc165 --- /dev/null +++ b/services/plan-manager/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/operations/trigger_management/exec_sample.go b/services/plan-manager/restapi/operations/trigger_management/exec_sample.go new file mode 100644 index 0000000..3a21c8a --- /dev/null +++ b/services/plan-manager/restapi/operations/trigger_management/exec_sample.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ExecSampleHandlerFunc turns a function with the right signature into a exec sample handler +type ExecSampleHandlerFunc func(ExecSampleParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ExecSampleHandlerFunc) Handle(params ExecSampleParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ExecSampleHandler interface for that can handle valid exec sample params +type ExecSampleHandler interface { + Handle(ExecSampleParams, interface{}) middleware.Responder +} + +// NewExecSample creates a new http.Handler for the exec sample operation +func NewExecSample(ctx *middleware.Context, handler ExecSampleHandler) *ExecSample { + return &ExecSample{Context: ctx, Handler: handler} +} + +/*ExecSample swagger:route GET /trigger/sample triggerManagement execSample + +Sample task trigger + +*/ +type ExecSample struct { + Context *middleware.Context + Handler ExecSampleHandler +} + +func (o *ExecSample) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewExecSampleParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/plan-manager/restapi/operations/trigger_management/exec_sample_parameters.go b/services/plan-manager/restapi/operations/trigger_management/exec_sample_parameters.go new file mode 100644 index 0000000..e3aad65 --- /dev/null +++ b/services/plan-manager/restapi/operations/trigger_management/exec_sample_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewExecSampleParams creates a new ExecSampleParams object +// no default values defined in spec. +func NewExecSampleParams() ExecSampleParams { + + return ExecSampleParams{} +} + +// ExecSampleParams contains all the bound params for the exec sample operation +// typically these are obtained from a http.Request +// +// swagger:parameters execSample +type ExecSampleParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewExecSampleParams() beforehand. +func (o *ExecSampleParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/plan-manager/restapi/operations/trigger_management/exec_sample_responses.go b/services/plan-manager/restapi/operations/trigger_management/exec_sample_responses.go new file mode 100644 index 0000000..f1b4fbe --- /dev/null +++ b/services/plan-manager/restapi/operations/trigger_management/exec_sample_responses.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" +) + +// ExecSampleOKCode is the HTTP code returned for type ExecSampleOK +const ExecSampleOKCode int = 200 + +/*ExecSampleOK Sample task executed successfully + +swagger:response execSampleOK +*/ +type ExecSampleOK struct { +} + +// NewExecSampleOK creates ExecSampleOK with default headers values +func NewExecSampleOK() *ExecSampleOK { + + return &ExecSampleOK{} +} + +// WriteResponse to the client +func (o *ExecSampleOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// ExecSampleInternalServerErrorCode is the HTTP code returned for type ExecSampleInternalServerError +const ExecSampleInternalServerErrorCode int = 500 + +/*ExecSampleInternalServerError Something unexpected happend, error raised + +swagger:response execSampleInternalServerError +*/ +type ExecSampleInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewExecSampleInternalServerError creates ExecSampleInternalServerError with default headers values +func NewExecSampleInternalServerError() *ExecSampleInternalServerError { + + return &ExecSampleInternalServerError{} +} + +// WithPayload adds the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) WithPayload(payload *models.ErrorResponse) *ExecSampleInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the exec sample internal server error response +func (o *ExecSampleInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ExecSampleInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/plan-manager/restapi/operations/trigger_management/exec_sample_urlbuilder.go b/services/plan-manager/restapi/operations/trigger_management/exec_sample_urlbuilder.go new file mode 100644 index 0000000..33b621a --- /dev/null +++ b/services/plan-manager/restapi/operations/trigger_management/exec_sample_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ExecSampleURL generates an URL for the exec sample operation +type ExecSampleURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) WithBasePath(bp string) *ExecSampleURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecSampleURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ExecSampleURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/sample" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ExecSampleURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ExecSampleURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ExecSampleURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ExecSampleURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ExecSampleURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ExecSampleURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/plan-manager/restapi/server.go b/services/plan-manager/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/services/plan-manager/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/services/plan-manager/run/cert.crt b/services/plan-manager/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/plan-manager/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/plan-manager/run/config.toml b/services/plan-manager/run/config.toml new file mode 100644 index 0000000..1bd9381 --- /dev/null +++ b/services/plan-manager/run/config.toml @@ -0,0 +1,89 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "23h" +DBName = "cyclops" +Host = "localhost" +Password = "pass1234" +Port = 5432 +# SSLMode = enable | disable +SSLMode = "disable" +UserName = "cyclops" + +[EVENTS] +Filters = [ "filter1", "filter2" ] + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +# "" for no file-logging +LogFile = "" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8000" +CDR = "cdr:8000" +CreditManager = "creditsystem:8000" +CustomerDB = "customerdb:8000" +EventsEngine = "eventsengine:8000" +PlanManager = "planmanager:8000" +UDR = "udr:8000" + +[KAFKA] +Brokers = [ "kafka1:9092", "kafka2:9092", "kafka3:9092" ] +CDRIn = [ "CDR" ] +CDROut = [ "Credit" ] +Credit-SystemIn = [ "Credit" ] +EventsEngineIn = [ "Events" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMin = 10e3 +SizeMax = 10e6 +UDRIn = [ "UDR" ] +UDROut = [ "CDR" ] + +[PLANS] +Default = "-1" +Education = "-2" + +[PROMETHEUS] +Host = "prometheus:9090" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + diff --git a/services/plan-manager/run/docker-compose.yml b/services/plan-manager/run/docker-compose.yml new file mode 100644 index 0000000..8a6e52e --- /dev/null +++ b/services/plan-manager/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: SERVICE:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/services/plan-manager/run/key.key b/services/plan-manager/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/plan-manager/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/plan-manager/server/bundleManager/bundleManager.go b/services/plan-manager/server/bundleManager/bundleManager.go new file mode 100644 index 0000000..7c00879 --- /dev/null +++ b/services/plan-manager/server/bundleManager/bundleManager.go @@ -0,0 +1,295 @@ +package bundleManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/bundle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// BundleManager is the struct defined to group and contain all the methods +// that interact with the bundle subsystem. +// Parameters: +// - basePath: a string with the base path of the system. +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type BundleManager struct { + basePath string + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct BundleManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// - bp: a string containing the base path of the service. +// Returns: +// - BundleManager: struct to interact with BundleManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *BundleManager { + + l.Trace.Printf("[BundleManager] Generating new bundleManager.\n") + + monit.InitEndpoint("bundle") + + return &BundleManager{ + basePath: bp, + db: db, + monit: monit, + } + +} + +// CreateSkuBundle (Swagger func) is the function behind the (POST) endpoint /bundle +// Its job is to add a new bundle to the system. +func (m *BundleManager) CreateSkuBundle(ctx context.Context, params bundle_management.CreateSkuBundleParams) middleware.Responder { + + l.Trace.Printf("[BundleManager] CreateSkuBundle endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bundle", callTime) + + id, state, e := m.db.CreateSkuBundle(params.Bundle) + + if e != nil { + + s := "Problem creating the new Bundle: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/sku/bundle"}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewCreateSkuBundleInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusDuplicated { + + s := "The Bundle already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/sku/bundle"}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewCreateSkuBundleConflict().WithPayload(&conflictReturn) + + } + + link := m.basePath + "/sku/bundle/" + id + + createdReturn := models.ItemCreatedResponse{ + ID: id, + Link: link, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/sku/bundle"}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewCreateSkuBundleCreated().WithPayload(&createdReturn) + +} + +// GetSkuBundle (Swagger func) is the function behind the (GET) endpoint /bundle/{id} +// Its job is to retrieve the bundle linked to the provided id. +func (m *BundleManager) GetSkuBundle(ctx context.Context, params bundle_management.GetSkuBundleParams) middleware.Responder { + + l.Trace.Printf("[BundleManager] GetSkuBundle endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bundle", callTime) + + bundle, e := m.db.GetSkuBundle(params.ID) + + if e != nil { + + s := "Problem retrieving the Bundle from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/sku/bundle/" + params.ID}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewGetSkuBundleInternalServerError().WithPayload(&errorReturn) + + } + + if bundle != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/sku/bundle/" + params.ID}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewGetSkuBundleOK().WithPayload(bundle) + + } + + s := "The Bundle doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/sku/bundle/" + params.ID}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewGetSkuBundleNotFound().WithPayload(&missingReturn) + +} + +// GetSkuBundleByName (Swagger func) is the function behind the (GET) endpoint +// /bundle/name/{name} +// Its job is to retrieve the bundle provided the name of the bundle. +func (m *BundleManager) GetSkuBundleByName(ctx context.Context, params bundle_management.GetSkuBundleByNameParams) middleware.Responder { + + l.Trace.Printf("[BundleManager] GetSkuBundleByName endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bundle", callTime) + + bundle, e := m.db.GetSkuBundleByName(params.Name) + + if e != nil { + + s := "Problem retrieving the Bundle from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/sku/bundle/name/" + params.Name}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewGetSkuBundleByNameInternalServerError().WithPayload(&errorReturn) + + } + + if bundle != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/sku/bundle/name/" + params.Name}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewGetSkuBundleByNameOK().WithPayload(bundle) + + } + + s := "The Bundle doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/sku/bundle/name/" + params.Name}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewGetSkuBundleByNameNotFound().WithPayload(&missingReturn) + +} + +// ListSkuBundles (Swagger func) is the function behind the (GET) endpoint /bundle +// Its job is to list all the bundles present in the system. +func (m *BundleManager) ListSkuBundles(ctx context.Context, params bundle_management.ListSkuBundlesParams) middleware.Responder { + + l.Trace.Printf("[BundleManager] ListSkuBundles endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bundle", callTime) + + bundles, e := m.db.ListSkuBundles() + + if e != nil { + + s := "Problem retrieving Bundles in the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/sku/bundle"}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewListSkuBundlesInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/sku/bundle"}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewListSkuBundlesOK().WithPayload(bundles) + +} + +// UpdateSkuBundle (Swagger func) is the function behind the (PUT) endpoint +// /sku/bundle/{id} +// Its job is to update the linked Sku bundle to the provided ID with the provided data. +func (m *BundleManager) UpdateSkuBundle(ctx context.Context, params bundle_management.UpdateSkuBundleParams) middleware.Responder { + + l.Trace.Printf("[BundleManager] UpdateSkuBundle endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("bundle", callTime) + + state, e := m.db.UpdateSkuBundle(params.ID, params.Bundle) + + if e != nil { + + s := "Problem updating Bundle: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/sku/bundle/" + params.ID}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewUpdateSkuBundleInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusMissing { + + s := "The Bundle doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/sku/bundle/" + params.ID}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewUpdateSkuBundleNotFound().WithPayload(&missingReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/sku/bundle/" + params.ID}).Inc() + + m.monit.APIHitDone("bundle", callTime) + + return bundle_management.NewUpdateSkuBundleOK().WithPayload(params.Bundle) + +} diff --git a/services/plan-manager/server/config.go b/services/plan-manager/server/config.go new file mode 100644 index 0000000..4eb0cf9 --- /dev/null +++ b/services/plan-manager/server/config.go @@ -0,0 +1,223 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + DefaultPlans map[string]string + Prometheus prometheusConfig +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type planConfig struct { + Default string +} +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("database.cacheretention"), + DbName: viper.GetString("database.dbname"), + Host: viper.GetString("database.host"), + Password: viper.GetString("database.password"), + Port: viper.GetInt("database.port"), + SSLMode: viper.GetString("database.sslmode"), + Username: viper.GetString("database.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + DefaultPlans: viper.GetStringMapString("plans"), + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/services/plan-manager/server/cycleManager/cycleManager.go b/services/plan-manager/server/cycleManager/cycleManager.go new file mode 100644 index 0000000..3756e51 --- /dev/null +++ b/services/plan-manager/server/cycleManager/cycleManager.go @@ -0,0 +1,260 @@ +package cycleManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/cycle_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// CycleManager is the struct defined to group and contain all the methods +// that interact with the cycle subsystem. +// Parameters: +// - basePath: a string with the base path of the system. +// - db: a DbParameter reference to be able to use the DBManager methods. +// - s.monit. a StatusManager reference to be able to use the status subsystem methods. +type CycleManager struct { + basePath string + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct CycleManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// - bp: a string containing the base path of the service. +// Returns: +// - CycleManager: struct to interact with CycleManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *CycleManager { + + l.Trace.Printf("[CycleManager] Generating new cycleManager.\n") + + monit.InitEndpoint("cycle") + + return &CycleManager{ + basePath: bp, + db: db, + monit: monit, + } + +} + +// CreateCycle (Swagger func) is the function behind the (POST) endpoint /cycle +// Its job is to add a new Cycle to the system. +func (m *CycleManager) CreateCycle(ctx context.Context, params cycle_management.CreateCycleParams) middleware.Responder { + + l.Trace.Printf("[CycleManager] CreateCycle endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("cycle", callTime) + + id, status, e := m.db.CreateCycle(params.Cycle) + + if e != nil { + + s := "Problem creating the new Cycle: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/cycle"}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewCreateCycleInternalServerError().WithPayload(&errorReturn) + + } + + if status == statusDuplicated { + + s := "The Cycle already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/cycle"}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewCreateCycleConflict().WithPayload(&conflictReturn) + + } + + link := m.basePath + "/cycle/" + id + + createReturn := models.ItemCreatedResponse{ + ID: id, + Link: link, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/cycle"}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewCreateCycleCreated().WithPayload(&createReturn) + +} + +// GetCycle (Swagger func) is the function behind the (GET) endpoint /cycle/{id} +// Its job is to get the Cycle linked to the provided id. +func (m *CycleManager) GetCycle(ctx context.Context, params cycle_management.GetCycleParams) middleware.Responder { + + l.Trace.Printf("[CycleManager] GetCycle endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("cycle", callTime) + + cycle, e := m.db.GetCycle(params.ID) + + if e != nil { + + s := "Problem retrieving the Cycle from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/cycle/" + params.ID}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewGetCycleInternalServerError().WithPayload(&errorReturn) + + } + + if cycle != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/cycle/" + params.ID}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewGetCycleOK().WithPayload(cycle) + + } + + s := "The Cycle doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/cycle/" + params.ID}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewGetCycleNotFound().WithPayload(&missingReturn) + +} + +// ListCycles (Swagger func) is the function behind the (GET) endpoint /cycle +// Its job is to get the list of Cycles in the system. +func (m *CycleManager) ListCycles(ctx context.Context, params cycle_management.ListCyclesParams) middleware.Responder { + + l.Trace.Printf("[CycleManager] ListCycles endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("cycle", callTime) + + state := "" + + if params.State != nil { + + state = *params.State + + } + + ty := "" + + if params.Type != nil { + + ty = *params.Type + + } + + cycles, e := m.db.ListCycles(state, ty) + + if e != nil { + + s := "Problem retrieving the Cycles from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/cycle"}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewListCyclesInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/cycle"}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewListCyclesOK().WithPayload(cycles) + +} + +// UpdateCycle (Swagger func) is the function behind the (PUT) endpoint /cycle/{id} +// Its job is to update the liked Cycle to the provided ID with the provided data. +func (m *CycleManager) UpdateCycle(ctx context.Context, params cycle_management.UpdateCycleParams) middleware.Responder { + + l.Trace.Printf("[CycleManager] UpdateCycle endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("cycle", callTime) + + state, e := m.db.UpdateCycle(params.ID, params.Cycle) + + if e != nil { + + s := "Problem updating the new Cycle: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/cycle/" + params.ID}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewUpdateCycleInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusMissing { + + s := "The Cycle doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/cycle/" + params.ID}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewUpdateCycleNotFound().WithPayload(&missingReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/cycle/" + params.ID}).Inc() + + m.monit.APIHitDone("cycle", callTime) + + return cycle_management.NewUpdateCycleOK().WithPayload(params.Cycle) + +} diff --git a/services/plan-manager/server/dbManager/dbManager.go b/services/plan-manager/server/dbManager/dbManager.go new file mode 100644 index 0000000..2d1b8ed --- /dev/null +++ b/services/plan-manager/server/dbManager/dbManager.go @@ -0,0 +1,834 @@ +package dbManager + +import ( + "errors" + + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// Parameters: +// - connStr: strings with the connection information to the database +// - Db: a gorm.DB pointer to the db to invoke all the db methods +type DbParameter struct { + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec +} + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization +// Returns: +// - DbParameter: struct to interact with dbManager functionalities +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + } + + l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + dp.Db.AutoMigrate(tables...) + + l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + //dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NewScope(&models.TABLE).TableName() + "', 'TIMESCALE-ROW-INDEX');") + + return &dp + +} + +// CreateCycle function is to add a new cycle to the system. +// Parameters: +// - p: a reference to Cycle models containing the new data to be stored +// in the system. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) CreateCycle(p *models.Cycle) (id string, status int, e error) { + + l.Trace.Printf("[DB] Attempting to create a new Cycle now.\n") + + var p0 models.Cycle + + if r := d.Db.Where(p).First(&p0).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + if r := d.Db.Create(p); r.Error == nil { + + l.Info.Printf("Inserted new record for cycle [ %v ] successfully.\n", *p.State) + + d.Metrics["count"].With(prometheus.Labels{"type": "Cycles added"}).Inc() + + status = statusOK + id = (*r.Statement.Model.(*models.Cycle)).ID + + } else { + + l.Warning.Printf("Unable to insert the record for cycle [ %v ], check with administrator.\n", *p.State) + + e = r.Error + status = statusFail + + } + + } else { + + l.Warning.Printf("Record for cycle [ %v ] already exists, check with administrator.\n", *p.State) + + status = statusDuplicated + + } + + return + +} + +// CreatePlan function is to add a new plan to the system. +// Parameters: +// - p: a reference to Plan models containing the new data to be stored +// in the system. +// Returns: +// - id: a string containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) CreatePlan(p *models.Plan) (id string, status int, e error) { + + l.Trace.Printf("[DB] Attempting to create a new Plan now.\n") + + var p0 models.Plan + + if r := d.Db.Where(p).First(&p0).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + if r := d.Db.Create(p); r.Error == nil { + + l.Info.Printf("Inserted new record for plan [ %v ] successfully.\n", *p.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Plans added"}).Inc() + + status = statusOK + id = (*r.Statement.Model.(*models.Plan)).ID + + } else { + + l.Warning.Printf("Unable to insert the record for plan [ %v ], check with administrator.\n", *p.Name) + + e = r.Error + status = statusFail + + } + + } else { + + l.Warning.Printf("Record for plan [ %v ] already exists, check with administrator.\n", *p.Name) + + status = statusDuplicated + + } + + return + +} + +// CreateSku function is to add a new sku to the system. +// Parameters: +// - s: a reference to Sku models containing the new data to be stored +// in the system. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) CreateSku(s *models.Sku) (id string, status int, e error) { + + l.Trace.Printf("[DB] Attempting to create a new Sku now.\n") + + var s0 models.Sku + + if r := d.Db.Where(s).First(&s0).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + if r := d.Db.Create(s); r.Error == nil { + + l.Info.Printf("Inserted new record for sku [ %v ] successfully.\n", *s.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Skus added"}).Inc() + + status = statusOK + id = (*r.Statement.Model.(*models.Sku)).ID + + } else { + + l.Warning.Printf("Unable to insert the record for sku [ %v ], check with administrator.\n", *s.Name) + + e = r.Error + status = statusFail + + } + + } else { + + l.Warning.Printf("Record for sku [ %v ] already exists, check with administrator.\n", *s.Name) + + status = statusDuplicated + + } + + return + +} + +// CreateSkuBundle function is to add a new bundle to the system. +// Parameters: +// - f: a reference to Bundle models containing the new data to be stored +// in the system. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) CreateSkuBundle(f *models.SkuBundle) (id string, status int, e error) { + + l.Trace.Printf("[DB] Attempting to create a new Bundle now.\n") + + var f0 models.SkuBundle + + if r := d.Db.Where(f).First(&f0).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + if r := d.Db.Create(f); r.Error == nil { + + l.Info.Printf("Inserted new record for bundle [ %v ] successfully.\n", *f.Name) + + d.Metrics["count"].With(prometheus.Labels{"type": "Bundles added"}).Inc() + + status = statusOK + id = (r.Statement.Model.(*models.SkuBundle)).ID + + } else { + + l.Warning.Printf("Unable to insert the record for bundle [ %v ], check with administrator.\n", *f.Name) + + e = r.Error + status = statusFail + + } + + } else { + + l.Warning.Printf("Record for bundle [ %v ] already exists, check with administrator. Error: %v\n", *f.Name, r) + + id = f0.ID + status = statusDuplicated + + } + + return + +} + +// CreateSkuPrice function is to add a new sku price to the system. +// Parameters: +// - sp: a reference to Sku Price models containing the new data to be stored +// in the system. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) CreateSkuPrice(sp *models.SkuPrice) (id string, status int, e error) { + + l.Trace.Printf("[DB] Attempting to create a new Sku Price now.\n") + + var sp0 models.SkuPrice + + if r := d.Db.Where(sp).First(&sp0).Error; errors.Is(r, gorm.ErrRecordNotFound) { + + if r := d.Db.Create(sp); r.Error == nil { + + l.Info.Printf("Inserted new record for sku price [ %v ] successfully.\n", sp.SkuName) + + d.Metrics["count"].With(prometheus.Labels{"type": "Sku Prices added"}).Inc() + + status = statusOK + id = (*r.Statement.Model.(*models.SkuPrice)).ID + + } else { + + l.Warning.Printf("Unable to insert the record for sku price [ %v ], check with administrator.\n", sp.SkuName) + + e = r.Error + status = statusFail + + } + + } else { + + l.Warning.Printf("Record for sku price [ %v ] already exists, check with administrator.\n", sp.SkuName) + + status = statusDuplicated + + } + + return + +} + +// GetCompletePlan function is to retrieve a completed plan (includings its +// linked skus) from the system provided its id. +// Parameters: +// - id: a string containing the id of the plan to be retrieved from the system. +// Returns: +// - reference to Plan model containing the requested one stored in the system. +// - error raised in case of problems with the operation. +func (d *DbParameter) GetCompletePlan(id string) (*models.Plan, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the Complete Plan [ %v ] now.\n", id) + + var object models.Plan + var e error + + if e = d.Db.Where(&models.Plan{ID: id}).First(&object).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Complete plan with id: %v doesn't exist in the system, check with administrator.", id) + + } + + d.Db.Where(&models.SkuPrice{PlanID: &object.ID}).Find(&object.SkuPrices) + + return &object, e + +} + +// GetCycle function is to retrieve a cycle from the system provided its id. +// Parameters: +// - id: an int64 containing the id of the cycle to be retrieved from the system. +// Returns: +// - reference to Cycle model containing the requested one stored in the system. +// - error raised in case of problems with the operation. +func (d *DbParameter) GetCycle(id string) (*models.Cycle, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the Cycle [ %v ] now.\n", id) + + var object models.Cycle + var e error + + if e = d.Db.Where(&models.Cycle{ID: id}).First(&object).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Cycle with id: %v doesn't exist in the system, check with administrator.", id) + + } + + return &object, e + +} + +// GetPlan function is to retrieve a plan from the system provided its id. +// Parameters: +// - id: a string containing the id of the plan to be retrieved from the system. +// Returns: +// - reference to Plan model containing the requested one stored in the system. +// - error raised in case of problems with the operation. +func (d *DbParameter) GetPlan(id string) (*models.Plan, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the Plan [ %v ] now.\n", id) + + var object models.Plan + var e error + + if e = d.Db.Where(&models.Plan{ID: id}).First(&object).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Plan with id: %v doesn't exist in the system, check with administrator.", id) + + } + + return &object, e + +} + +// GetSku function is to retrieve a sku from the system provided its id. +// Parameters: +// - id: an int64 containing the id of the sku to be retrieved from the system. +// Returns: +// - reference to Sku model containing the requested one stored in the system. +// - error raised in case of problems with the operation. +func (d *DbParameter) GetSku(id string) (*models.Sku, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the Sku [ %v ] now.\n", id) + + var object models.Sku + var e error + + if e = d.Db.Where(&models.Sku{ID: id}).First(&object).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Sku with id: %v doesn't exist in the system, check with administrator.", id) + + } + + return &object, e + +} + +// GetSkuBundle function is to retrieve a bundle from the system provided its id. +// Parameters: +// - id: an int64 containing the id of the bundle to be retrieved from the system. +// Returns: +// - reference to Bundle model containing the requested one stored in the system. +// - error raised in case of problems with the operation. +func (d *DbParameter) GetSkuBundle(id string) (*models.SkuBundle, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the Bundle [ %v ] now.\n", id) + + var object models.SkuBundle + var e error + + if e = d.Db.Where(&models.SkuBundle{ID: id}).First(&object).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Bundle with id: %v doesn't exist in the system, check with administrator.", id) + + } + + return &object, e + +} + +// GetSkuBundleByName function is to retrieve a bundle from the system provided its +// name. +// Parameters: +// - name: a string containing the name of the bundle to be retrieved from the system. +// Returns: +// - reference to Bundle model containing the requested one stored in the system. +// - error raised in case of problems with the operation. +func (d *DbParameter) GetSkuBundleByName(name string) (*models.SkuBundle, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the Bundle [ %v ] now.\n", name) + + var object models.SkuBundle + var e error + + if e = d.Db.Where(&models.SkuBundle{Name: &name}).First(&object).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Bundle with name: %v doesn't exist in the system, check with administrator.", name) + + } + + return &object, e + +} + +// GetSkuPrice function is to retrieve a sku price from the system provided its id. +// Parameters: +// - id: an int64 containing the id of the sku price to be retrieved from the system. +// Returns: +// - reference to Sku Price model containing the requested one stored in the system. +// - error raised in case of problems with the operation. +func (d *DbParameter) GetSkuPrice(id string) (*models.SkuPrice, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the Sku Price [ %v ] now.\n", id) + + var object models.SkuPrice + var e error + + if e = d.Db.Where(&models.SkuPrice{ID: id}).First(&object).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + l.Trace.Printf("[DB] Sku price with id: %v doesn't exist in the system, check with administrator.", id) + + } + + return &object, e + +} + +// ListCompletePlans function is to retrieve all the complete plans (with the +// linked skus) contained in the system. +// Returns: +// - p: a reference to Plan models containing the list of them stored in the system. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) ListCompletePlans() (p []*models.Plan, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the Complete Plans in the system now.\n") + + var p0 []*models.Plan + + if e := d.Db.Find(&p0).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + for i := range p0 { + + plan := p0[i] + d.Db.Where(&models.SkuPrice{PlanID: &p0[i].ID}).Find(&plan.SkuPrices) + + p = append(p, plan) + + } + + l.Trace.Printf("[DB] Found [ %d ] complete plans in the db.\n", len(p)) + + return + +} + +// ListCycles function is to retrieve all the cycles contained in the system. +// Returns: +// - p: a reference to Cycle models containing the list of them stored in the system. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) ListCycles(state, ty string) (p []*models.Cycle, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the Cycles in the system now.\n") + + var c models.Cycle + + if state != "" { + + c.State = &state + + } + + if ty != "" { + + c.ResourceType = &ty + + } + + if e := d.Db.Where(&c).Find(&p).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] cycles in the db.\n", len(p)) + + return + +} + +// ListPlans function is to retrieve all the plans contained in the system. +// Returns: +// - p: a reference to Plan models containing the list of them stored in the system. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) ListPlans() (p []*models.Plan, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the Plans in the system now.\n") + + if e := d.Db.Find(&p).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] plans in the db.\n", len(p)) + + return + +} + +// ListSkuBundles function is to retrieve all the bundles contained in the system. +// Returns: +// - f: a reference to Bundle models containing the list of them stored in the system. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) ListSkuBundles() (f []*models.SkuBundle, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the Bundles in the system now.\n") + + if e := d.Db.Find(&f).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] bundles in the db.\n", len(f)) + + return + +} + +// ListSkuPrices function is to retrieve all the sku prices contained in the system. +// Returns: +// - sp: a reference to Sku Price models containing the list of them stored in the system. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) ListSkuPrices() (sp []*models.SkuPrice, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the Sku Prices in the system now.\n") + + if e := d.Db.Find(&sp).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] sku prices in the db.\n", len(sp)) + + return + +} + +// ListSkus function is to retrieve all the skus contained in the system. +// Returns: +// - s: a reference to Sku models containing the list of them stored in the system. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) ListSkus() (s []*models.Sku, e error) { + + l.Trace.Printf("[DB] Attempting to retrieve all the Skus in the system now.\n") + + if e := d.Db.Find(&s).Error; e != nil { + + l.Warning.Printf("[DB] Error in DB operation. Error: %v\n", e) + + } + + l.Trace.Printf("[DB] Found [ %d ] skus in the db.\n", len(s)) + + return + +} + +// UpdateCycle function is to update the cycle linked to the provided ID +// with the provided new data. +// Parameters: +// - id: an int64 containing the id of the sku price to be updated in the db. +// - p: a reference to Cycle models containing the new data to be updated. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) UpdateCycle(id string, p *models.Cycle) (status int, e error) { + + l.Trace.Printf("[DB] Attempting to update the Cycle [ %v ] now.\n", id) + + var p0 models.Cycle + + if r := d.Db.Where(&models.Cycle{ID: id}).First(&p0).Error; !errors.Is(r, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&p0).Updates(p).Error; e == nil { + + l.Info.Printf("[DB] Updated record for cycle [ %v ] successfully.\n", p.ID) + + d.Metrics["count"].With(prometheus.Labels{"type": "Cycles updated"}).Inc() + + status = statusOK + + } else { + + l.Warning.Printf("[DB] Unable to update record for cycle [ %v ], check with administrator.\n", p.ID) + + status = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for cycle [ %v ] not found, check with administrator.\n", p.ID) + + status = statusMissing + + } + + return + +} + +// UpdatePlan function is to update the plan linked to the provided ID +// with the provided new data. +// Parameters: +// - id: a string containing the id of the sku price to be updated in the db. +// - p: a reference to Plan models containing the new data to be updated. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) UpdatePlan(id string, p *models.Plan) (status int, e error) { + + l.Trace.Printf("[DB] Attempting to update the Plan [ %v ] now.\n", id) + + var p0 models.Plan + + if r := d.Db.Where(&models.Plan{ID: id}).First(&p0).Error; !errors.Is(r, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&p0).Updates(p).Error; e == nil { + + l.Info.Printf("[DB] Updated record for plan [ %v ] successfully.\n", p.ID) + + d.Metrics["count"].With(prometheus.Labels{"type": "Plans updated"}).Inc() + + status = statusOK + + } else { + + l.Warning.Printf("[DB] Unable to update record for plan [ %v ], check with administrator.\n", p.ID) + + status = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for plan [ %v ] not found, check with administrator.\n", p.ID) + + status = statusMissing + + } + + return + +} + +// UpdateSku function is to update the sku linked to the provided ID +// with the provided new data. +// Parameters: +// - id: an int64 containing the id of the sku price to be updated in the db. +// - s: a reference to Sku models containing the new data to be updated. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) UpdateSku(id string, s *models.Sku) (status int, e error) { + + l.Trace.Printf("[DB] Attempting to update the Sku [ %v ] now.\n", id) + + var s0 models.Sku + + if r := d.Db.Where(&models.Sku{ID: id}).First(&s0).Error; !errors.Is(r, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&s0).Updates(s).Error; e == nil { + + l.Info.Printf("[DB] Updated record for sku [ %v ] successfully.\n", s.ID) + + d.Metrics["count"].With(prometheus.Labels{"type": "Skus updated"}).Inc() + + status = statusOK + + } else { + + l.Warning.Printf("[DB] Unable to update record for sku [ %v ], check with administrator.\n", s.ID) + + status = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for sku [ %v ] not found, check with administrator.\n", s.ID) + + status = statusMissing + + } + + return + +} + +// UpdateSkuBundle function is to update the bundle linked to the provided ID +// with the provided new data. +// Parameters: +// - f: a reference to Bundle models containing the new data to be updated. +// Returns: +// - id: an int64 containing the id of the bundle just added to the db. +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) UpdateSkuBundle(id string, b *models.SkuBundle) (status int, e error) { + + l.Trace.Printf("[DB] Attempting to update the Bundle [ %v ] now.\n", b.ID) + + var b0 models.SkuBundle + + if r := d.Db.Where(&models.SkuBundle{ID: id}).First(&b0).Error; !errors.Is(r, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&b0).Updates(b).Error; e == nil { + + l.Info.Printf("[DB] Updated record for bundle [ %v ] successfully.\n", b.ID) + + d.Metrics["count"].With(prometheus.Labels{"type": "Bundles updated"}).Inc() + + status = statusOK + + } else { + + l.Warning.Printf("[DB] Unable to update record for bundle [ %v ], check with administrator.\n", b.ID) + + status = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for bundle [ %v ] not found, check with administrator.\n", b.ID) + + status = statusMissing + + } + + return + +} + +// UpdateSkuPrice function is to update the sku price linked to the provided ID +// with the provided new data. +// Parameters: +// - id: an int64 containing the id of the sku price to be updated in the db. +// - sp: a reference to SkuPrice models containing the new data to be updated. +// Returns: +// - status: an int for informing about the status of the operation. +// - e: an error raised in case of problems with the operation. +func (d *DbParameter) UpdateSkuPrice(id string, sp *models.SkuPrice) (status int, e error) { + + l.Trace.Printf("[DB] Attempting to update the Sku Price [ %v ] now.\n", id) + + var sp0 models.SkuPrice + + if r := d.Db.Where(&models.SkuPrice{ID: id}).First(&sp0).Error; !errors.Is(r, gorm.ErrRecordNotFound) { + + if e := d.Db.Model(&sp0).Updates(sp).Error; e == nil { + + l.Info.Printf("[DB] Updated record for sku price [ %v ] successfully.\n", sp.ID) + + d.Metrics["count"].With(prometheus.Labels{"type": "Sku Prices updated"}).Inc() + + status = statusOK + + } else { + + l.Warning.Printf("[DB] Unable to update record for sku price [ %v ], check with administrator.\n", sp.ID) + + status = statusFail + + } + + } else { + + l.Warning.Printf("[DB] Record for sku price [ %v ] not found, check with administrator.\n", sp.ID) + + status = statusMissing + + } + + return + +} diff --git a/services/plan-manager/server/main.go b/services/plan-manager/server/main.go new file mode 100644 index 0000000..52b11b6 --- /dev/null +++ b/services/plan-manager/server/main.go @@ -0,0 +1,176 @@ +package main + +import ( + "crypto/tls" + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/services/plan-manager/server/metrics.go b/services/plan-manager/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/services/plan-manager/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/services/plan-manager/server/planManager/planManager.go b/services/plan-manager/server/planManager/planManager.go new file mode 100644 index 0000000..99c0047 --- /dev/null +++ b/services/plan-manager/server/planManager/planManager.go @@ -0,0 +1,330 @@ +package planManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/plan_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// PlanManager is the struct defined to group and contain all the methods +// that interact with the plan subsystem. +// Parameters: +// - basePath: a string with the base path of the system. +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type PlanManager struct { + basePath string + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct PlanManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// - bp: a string containing the base path of the service. +// Returns: +// - PlanManager: struct to interact with PlanManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *PlanManager { + + l.Trace.Printf("[PlanManager] Generating new planManager.\n") + + monit.InitEndpoint("plan") + + return &PlanManager{ + basePath: bp, + db: db, + monit: monit, + } + +} + +// CreatePlan (Swagger func) is the function behind the (POST) endpoint /plan +// Its job is to add a new plan in the system. +func (m *PlanManager) CreatePlan(ctx context.Context, params plan_management.CreatePlanParams) middleware.Responder { + + l.Trace.Printf("[PlanManager] CreatePlan endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("plan", callTime) + + id, state, e := m.db.CreatePlan(params.Plan) + + if e != nil { + + s := "Problem creating the new Plan: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/plan"}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewCreatePlanInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusDuplicated { + + s := "The Plan already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/plan"}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewCreatePlanConflict().WithPayload(&conflictReturn) + + } + + link := m.basePath + "/plan/" + id + + createReturn := models.ItemCreatedResponse{ + ID: id, + Link: link, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "GET", "route": "/plan"}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewCreatePlanCreated().WithPayload(&createReturn) + +} + +// GetCompletePlan (Swagger func) is the function behind the (GET) endpoint +// /plan/complete/{id} +// Its job is to retrieve the full information related to a plan provided its ID. +func (m *PlanManager) GetCompletePlan(ctx context.Context, params plan_management.GetCompletePlanParams) middleware.Responder { + + l.Trace.Printf("[PlanManager] GetCompletePlan endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("plan", callTime) + + plan, e := m.db.GetCompletePlan(params.ID) + + if e != nil { + + s := "Problem retrieving the Plan from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/plan/complete/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewGetCompletePlanInternalServerError().WithPayload(&errorReturn) + + } + + if plan != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/plan/complete/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewGetCompletePlanOK().WithPayload(plan) + + } + + s := "The Plan doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/plan/complete/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewGetCompletePlanNotFound().WithPayload(&missingReturn) + +} + +// GetPlan (Swagger func) is the function behind the (GET) endpoint /plan/{id} +// Its job is to retrieve the information related to a plan provided its ID. +func (m *PlanManager) GetPlan(ctx context.Context, params plan_management.GetPlanParams) middleware.Responder { + + l.Trace.Printf("[PlanManager] GetPlan endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("plan", callTime) + + plan, e := m.db.GetPlan(params.ID) + + if e != nil { + + s := "Problem retrieving the Plan from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/plan/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewGetPlanInternalServerError().WithPayload(&errorReturn) + + } + + if plan != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/plan/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewGetPlanOK().WithPayload(plan) + + } + + s := "The Plan doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/plan/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewGetPlanNotFound().WithPayload(&missingReturn) + +} + +// ListCompletePlans (Swagger func) is the function behind the (GET) endpoint +// /plan/complete +// Its job is to retrieve the full information, including linked skus, related +// to a plan provided its ID. +func (m *PlanManager) ListCompletePlans(ctx context.Context, params plan_management.ListCompletePlansParams) middleware.Responder { + + l.Trace.Printf("[PlanManager] ListCompletePlans endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("plan", callTime) + + plans, e := m.db.ListCompletePlans() + + if e != nil { + + s := "Problem retrieving the Plan from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/plan/complete"}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewListCompletePlansInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/plan/complete"}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewListCompletePlansOK().WithPayload(plans) + +} + +// ListPlans (Swagger func) is the function behind the (GET) endpoint /plan +// Its job is to retrieve the information related to a plan provided its ID. +func (m *PlanManager) ListPlans(ctx context.Context, params plan_management.ListPlansParams) middleware.Responder { + + l.Trace.Printf("[PlanManager] ListPlans endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("plan", callTime) + + plans, e := m.db.ListPlans() + + if e != nil { + + s := "Problem retrieving the Plan from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/plan"}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewListPlansInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/plan"}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewListPlansOK().WithPayload(plans) + +} + +// UpdatePlan (Swagger func) is the function behind the (PUT) endpoint /plan/{id} +// Its job is to update the plan linked to the provided ID with the new plan data. +func (m *PlanManager) UpdatePlan(ctx context.Context, params plan_management.UpdatePlanParams) middleware.Responder { + + l.Trace.Printf("[PlanManager] UpdatePlan endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("plan", callTime) + + state, e := m.db.UpdatePlan(params.ID, params.Plan) + + if e != nil { + + s := "Problem retrieving the Plan from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/plan/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewUpdatePlanInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusMissing { + + s := "The Plan doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/plan/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewUpdatePlanNotFound().WithPayload(&missingReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/plan/" + params.ID}).Inc() + + m.monit.APIHitDone("plan", callTime) + + return plan_management.NewUpdatePlanOK().WithPayload(params.Plan) + +} diff --git a/services/plan-manager/server/priceManager/priceManager.go b/services/plan-manager/server/priceManager/priceManager.go new file mode 100644 index 0000000..81c1a74 --- /dev/null +++ b/services/plan-manager/server/priceManager/priceManager.go @@ -0,0 +1,246 @@ +package priceManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/price_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// PriceManager is the struct defined to group and contain all the methods +// that interact with the sku subsystem. +// Parameters: +// - basePath: a string with the base path of the system. +// - db: a DbParameter reference to be able to use the DBManager methods. +// - s.monit. a StatusManager reference to be able to use the status subsystem methods. +type PriceManager struct { + basePath string + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct PriceManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// - bp: a string containing the base path of the service. +// Returns: +// - PriceManager: struct to interact with PriceManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *PriceManager { + + l.Trace.Printf("[PriceManager] Generating new priceManager.\n") + + monit.InitEndpoint("price") + + return &PriceManager{ + basePath: bp, + db: db, + monit: monit, + } + +} + +// CreateSkuPrice (Swagger func) is the function behind the (POST) endpoint +// /sku/price +// Its job is to add a new Sku price to the system. +func (m *PriceManager) CreateSkuPrice(ctx context.Context, params price_management.CreateSkuPriceParams) middleware.Responder { + + l.Trace.Printf("[PriceManager] CreateSkuPrice endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("price", callTime) + + id, state, e := m.db.CreateSkuPrice(params.Price) + + if e != nil { + + s := "Problem creating the new Sku Price: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/sku/price"}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewCreateSkuPriceInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusDuplicated { + + s := "The Sku Price already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/sku/price"}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewCreateSkuPriceConflict().WithPayload(&conflictReturn) + + } + + link := m.basePath + "/sku/price/" + id + + createReturn := models.ItemCreatedResponse{ + ID: id, + Link: link, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/sku/price"}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewCreateSkuPriceCreated().WithPayload(&createReturn) + +} + +// GetSkuPrice (Swagger func) is the function behind the () endpoint /sku/price/{id} +// Its job is to get the Sku price linked to the provided id. +func (m *PriceManager) GetSkuPrice(ctx context.Context, params price_management.GetSkuPriceParams) middleware.Responder { + + l.Trace.Printf("[PriceManager] GetSkuPrice endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("price", callTime) + + sku, e := m.db.GetSkuPrice(params.ID) + + if e != nil { + + s := "Problem creating the new Sku Price: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/sku/price/" + params.ID}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewGetSkuPriceInternalServerError().WithPayload(&errorReturn) + + } + + if sku != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/sku/price/" + params.ID}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewGetSkuPriceOK().WithPayload(sku) + + } + + s := "The Sku Price doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/sku/price/" + params.ID}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewGetSkuPriceNotFound().WithPayload(&missingReturn) + +} + +// ListSkuPrices (Swagger func) is the function behind the (GET) endpoint /sku/price +// Its job is to get the list of Sku prices in the system. +func (m *PriceManager) ListSkuPrices(ctx context.Context, params price_management.ListSkuPricesParams) middleware.Responder { + + l.Trace.Printf("[PriceManager] ListSkuPrices endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("price", callTime) + + skus, e := m.db.ListSkuPrices() + + if e != nil { + + s := "Problem creating the new Sku Price: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/sku/price"}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewListSkuPricesInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/sku/price"}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewListSkuPricesOK().WithPayload(skus) + +} + +// UpdateSkuPrice (Swagger func) is the function behind the (PUT) endpoint +// /sku/price/{id} +// Its job is to update the liked Sku price to the provided ID with the provided data. +func (m *PriceManager) UpdateSkuPrice(ctx context.Context, params price_management.UpdateSkuPriceParams) middleware.Responder { + + l.Trace.Printf("[PriceManager] UpdateSkuPrice endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("price", callTime) + + state, e := m.db.UpdateSkuPrice(params.ID, params.Price) + + if e != nil { + + s := "Problem creating the new Sku Price: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/sku/price" + params.ID}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewUpdateSkuPriceInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusMissing { + + s := "The Sku Price doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/sku/price/" + params.ID}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewUpdateSkuPriceNotFound().WithPayload(&missingReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/sku/price/" + params.ID}).Inc() + + m.monit.APIHitDone("price", callTime) + + return price_management.NewUpdateSkuPriceOK().WithPayload(params.Price) + +} diff --git a/services/plan-manager/server/security.go b/services/plan-manager/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/services/plan-manager/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/services/plan-manager/server/service.go b/services/plan-manager/server/service.go new file mode 100644 index 0000000..fd59f6d --- /dev/null +++ b/services/plan-manager/server/service.go @@ -0,0 +1,85 @@ +package main + +import ( + "net/http" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/bundleManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/cycleManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/planManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/priceManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/skuManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,...,N have to be customized + db := dbStart(&models.Cycle{}, &models.Plan{}, &models.Sku{}, &models.SkuBundle{}, &models.SkuPrice{}) + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + bp := getBasePath() + + // Parts of the service HERE + b := bundleManager.New(db, mon, bp) + c := cycleManager.New(db, mon, bp) + p := planManager.New(db, mon, bp) + s := skuManager.New(db, mon, bp) + sp := priceManager.New(db, mon, bp) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + BundleManagementAPI: b, + CycleManagementAPI: c, + PlanManagementAPI: p, + SkuManagementAPI: s, + PriceManagementAPI: sp, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} diff --git a/services/plan-manager/server/skuManager/skuManager.go b/services/plan-manager/server/skuManager/skuManager.go new file mode 100644 index 0000000..0a4eeaa --- /dev/null +++ b/services/plan-manager/server/skuManager/skuManager.go @@ -0,0 +1,244 @@ +package skuManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/sku_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// SkuManager is the struct defined to group and contain all the methods +// that interact with the sku subsystem. +// Parameters: +// - basePath: a string with the base path of the system. +// - db: a DbParameter reference to be able to use the DBManager methods. +// - s.monit. a StatusManager reference to be able to use the status subsystem methods. +type SkuManager struct { + basePath string + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct SkuManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// - bp: a string containing the base path of the service. +// Returns: +// - SkuManager: struct to interact with SkuManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, bp string) *SkuManager { + + l.Trace.Printf("[SkuManager] Generating new skuManager.\n") + + monit.InitEndpoint("sku") + + return &SkuManager{ + basePath: bp, + db: db, + monit: monit, + } + +} + +// CreateSku (Swagger func) is the function behind the (POST) endpoint /sku +// Its job is to add a new Sku to the system. +func (m *SkuManager) CreateSku(ctx context.Context, params sku_management.CreateSkuParams) middleware.Responder { + + l.Trace.Printf("[SkuManager] CreateSku endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("sku", callTime) + + id, state, e := m.db.CreateSku(params.Sku) + + if e != nil { + + s := "Problem creating the new Sku: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "POST", "route": "/sku"}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewCreateSkuInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusDuplicated { + + s := "The Sku already exists in the system." + conflictReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "409", "method": "POST", "route": "/sku"}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewCreateSkuConflict().WithPayload(&conflictReturn) + + } + + link := m.basePath + "/sku/" + id + + createReturn := models.ItemCreatedResponse{ + ID: id, + Link: link, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "201", "method": "POST", "route": "/sku"}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewCreateSkuCreated().WithPayload(&createReturn) + +} + +// GetSku (Swagger func) is the function behind the (GET) endpoint /sku/{id} +// Its job is to get the Sku linked to the provided id. +func (m *SkuManager) GetSku(ctx context.Context, params sku_management.GetSkuParams) middleware.Responder { + + l.Trace.Printf("[SkuManager] GetSku endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("sku", callTime) + + sku, e := m.db.GetSku(params.ID) + + if e != nil { + + s := "Problem retrieving the Sku from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/sku/" + params.ID}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewGetSkuInternalServerError().WithPayload(&errorReturn) + + } + + if sku != nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/sku/" + params.ID}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewGetSkuOK().WithPayload(sku) + + } + + s := "The Sku doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/sku/" + params.ID}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewGetSkuNotFound().WithPayload(&missingReturn) + +} + +// ListSkus (Swagger func) is the function behind the (GET) endpoint /sku +// Its job is to get the list of Skus in the system. +func (m *SkuManager) ListSkus(ctx context.Context, params sku_management.ListSkusParams) middleware.Responder { + + l.Trace.Printf("[SkuManager] ListSkus endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("sku", callTime) + + skus, e := m.db.ListSkus() + + if e != nil { + + s := "Problem retrieving the Skus from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/sku"}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewListSkusInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/sku"}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewListSkusOK().WithPayload(skus) + +} + +// UpdateSku (Swagger func) is the function behind the (PUT) endpoint /sku/{id} +// Its job is to update the liked Sku to the provided ID with the provided data. +func (m *SkuManager) UpdateSku(ctx context.Context, params sku_management.UpdateSkuParams) middleware.Responder { + + l.Trace.Printf("[SkuManager] UpdateSku endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("sku", callTime) + + state, e := m.db.UpdateSku(params.ID, params.Sku) + + if e != nil { + + s := "Problem updating the Sku in the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "PUT", "route": "/sku/" + params.ID}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewUpdateSkuInternalServerError().WithPayload(&errorReturn) + + } + + if state == statusMissing { + + s := "The Sku doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "PUT", "route": "/sku/" + params.ID}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewUpdateSkuNotFound().WithPayload(&missingReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "PUT", "route": "/sku/" + params.ID}).Inc() + + m.monit.APIHitDone("sku", callTime) + + return sku_management.NewUpdateSkuOK().WithPayload(params.Sku) + +} diff --git a/services/plan-manager/server/statusManager/statusManager.go b/services/plan-manager/server/statusManager/statusManager.go new file mode 100644 index 0000000..f86acd8 --- /dev/null +++ b/services/plan-manager/server/statusManager/statusManager.go @@ -0,0 +1,325 @@ +package statusManager + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 + mutex *sync.Mutex +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + mutex = &sync.Mutex{} + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + avgTime[key] = t.UnixNano() + mutex.Unlock() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + previous, exists := avgTime[key] + mutex.Unlock() + + if exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + mutex.Lock() + delete(avgTime, key) + mutex.Unlock() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/services/plan-manager/server/triggerManager/triggerManager.go b/services/plan-manager/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..692a75f --- /dev/null +++ b/services/plan-manager/server/triggerManager/triggerManager.go @@ -0,0 +1,61 @@ +package triggerManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// TriggerManager is the struct defined to group and contain all the methods +// that interact with the trigger subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type TriggerManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct TriggerManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the StatusManager methods. +// Returns: +// - TriggerManager: struct to interact with triggerManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *TriggerManager { + + l.Trace.Printf("[Trigger] Generating new triggerManager.\n") + + monit.InitEndpoint("trigger") + + return &TriggerManager{ + db: db, + monit: monit, + } + +} + +// ExecSample (Swagger func) is the function behind the /trigger/sample endpoint. +// It is a dummy function for reference. +func (m *TriggerManager) ExecSample(ctx context.Context, params trigger_management.ExecSampleParams) middleware.Responder { + + l.Trace.Printf("[Trigger] ExecSample endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/trigger/sample"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecSampleOK() + +} diff --git a/services/plan-manager/swagger.yaml b/services/plan-manager/swagger.yaml new file mode 100644 index 0000000..52de66b --- /dev/null +++ b/services/plan-manager/swagger.yaml @@ -0,0 +1,962 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v1.0" +info: + description: An API which supports creation, deletion, listing etc of Plan Manager + version: "1.0.0" + title: Plan Manager Management API + contact: + email: sean@cyclops-labs.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + - name: bundleManagement + description: Actions relating to management of sku bundles + - name: cycleManagement + description: Actions relating to management of life cycles + - name: planManagement + description: Actions relating to management of plans + - name: priceManagement + description: Actions relating to management of sku prices + - name: skuManagement + description: Actions relating to management of skus and prices + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - kafka-receiver + - kafka-sender + - status + - trigger + - bundle + - cycle + - plan + - price + - sku + required: true + description: Id of the endpoint to be checked + /trigger/sample: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Sample task trigger + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: execSample + responses: + '200': + description: Sample task executed successfully + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + + /cycle: + get: + tags: + - cycleManagement + summary: List all cycles + operationId: listCycles + description: lists all cycles + responses: + '200': + description: list of cycles returned + schema: + type: array + items: + $ref: "#/definitions/Cycle" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: state to filter + in: query + name: state + type: string + - description: resource type to filter + in: query + name: type + type: string + post: + tags: + - cycleManagement + consumes: + - application/json + produces: + - application/json + summary: Create a plan + operationId: createCycle + description: Creates a new cycle + responses: + '201': + description: item created + schema: + $ref: "#/definitions/ItemCreatedResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + '400': + description: 'invalid input, object invalid' + '409': + description: an existing item already exists + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Cycle to be added + in: body + name: cycle + schema: + $ref: '#/definitions/Cycle' + /cycle/{id}: + get: + tags: + - cycleManagement + consumes: + - application/json + produces: + - application/json + summary: Get specific cycle + operationId: getCycle + description: get cycle with given id + responses: + '200': + description: cycle returned + schema: + $ref: "#/definitions/Cycle" + '404': + description: cycle with id not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of cycle to be obtained + in: path + name: id + required: true + type: string + put: + tags: + - cycleManagement + consumes: + - application/json + produces: + - application/json + summary: Update specific cycle + operationId: updateCycle + description: Update cycle with given id + responses: + '200': + description: updated cycle + schema: + $ref: "#/definitions/Cycle" + '404': + description: cycle with id not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of cycle to be updated + in: path + name: id + required: true + type: string + - description: updated cycle containing all parameters except id + in: body + name: cycle + required: true + schema: + $ref: "#/definitions/Cycle" + + /plan: + get: + tags: + - planManagement + summary: List all plans + operationId: listPlans + description: lists all plans (tbd - pagination?) + responses: + '200': + description: list of plans returned + schema: + type: array + items: + $ref: "#/definitions/Plan" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + post: + tags: + - planManagement + consumes: + - application/json + produces: + - application/json + summary: Create a plan + operationId: createPlan + description: Creates a new plan + responses: + '201': + description: item created + schema: + $ref: "#/definitions/ItemCreatedResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + '400': + description: 'invalid input, object invalid' + '409': + description: an existing item already exists + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Plan to be added + in: body + name: plan + schema: + $ref: '#/definitions/Plan' + /plan/{id}: + get: + tags: + - planManagement + consumes: + - application/json + produces: + - application/json + summary: Get specific plan + operationId: getPlan + description: get plan with given planid + responses: + '200': + description: plan returned + schema: + $ref: "#/definitions/Plan" + '404': + description: plan with planid not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of plan to be obtained + in: path + name: id + required: true + type: string + put: + tags: + - planManagement + consumes: + - application/json + produces: + - application/json + summary: Update specific plan + operationId: updatePlan + description: Update plan with given planId + responses: + '200': + description: updated plan + schema: + $ref: "#/definitions/Plan" + '404': + description: plan with planid not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of plan to be obtained + in: path + name: id + required: true + type: string + - description: updated plan containing all parameters except id + in: body + name: plan + required: true + schema: + $ref: "#/definitions/Plan" + /plan/complete: + get: + tags: + - planManagement + consumes: + - application/json + produces: + - application/json + summary: Get full information relating to known plans + operationId: listCompletePlans + description: Obtains full information on all known plans + responses: + '200': + description: Set of known plans returned in full + schema: + type: array + items: + $ref: "#/definitions/Plan" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + /plan/complete/{id}: + get: + tags: + - planManagement + consumes: + - application/json + produces: + - application/json + summary: Get complete plan + operationId: getCompletePlan + description: gets complete plan with planid + responses: + '200': + description: plan returned + schema: + $ref: "#/definitions/Plan" + '404': + description: complete plan with planid not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of plan to be obtained + in: path + name: id + required: true + type: string + + /sku: + get: + tags: + - skuManagement + summary: list SKUs + operationId: listSkus + description: lists all skus + responses: + '200': + description: list of skus returned + schema: + type: array + items: + $ref: "#/definitions/Sku" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + post: + tags: + - skuManagement + consumes: + - application/json + produces: + - application/json + summary: create SKU + operationId: createSku + description: Creates a new sku + responses: + '201': + description: item created + schema: + $ref: "#/definitions/ItemCreatedResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + '400': + description: invalid input, object invalid + '409': + description: an existing item already exists + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: SKU to be added + in: body + name: sku + schema: + $ref: '#/definitions/Sku' + /sku/{id}: + get: + tags: + - skuManagement + consumes: + - application/json + produces: + - application/json + summary: Get specific sku + operationId: getSku + description: get sku with given skuid + responses: + '200': + description: sku returned + schema: + $ref: "#/definitions/Sku" + '404': + description: sku with skuid not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of sku to be obtained + in: path + name: id + required: true + type: string + put: + tags: + - skuManagement + consumes: + - application/json + produces: + - application/json + summary: Update specific sku + operationId: updateSku + description: Update sku with given skuid + responses: + '200': + description: updated sku + schema: + $ref: "#/definitions/Sku" + '404': + description: sku with skuid not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of sku to be obtained + in: path + name: id + required: true + type: string + - description: updated sku containing all parameters except id + in: body + name: sku + required: true + schema: + $ref: "#/definitions/Sku" + + /sku/bundle: + get: + tags: + - bundleManagement + summary: list SKU Bundles + operationId: listSkuBundles + description: lists all sku bundles + responses: + '200': + description: list of skus bundles returned + schema: + type: array + items: + $ref: "#/definitions/SkuBundle" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + post: + tags: + - bundleManagement + consumes: + - application/json + produces: + - application/json + summary: create SKU bundle + operationId: createSkuBundle + description: Creates a new sku bundle + responses: + '201': + description: item created + schema: + $ref: "#/definitions/ItemCreatedResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + '400': + description: invalid input, object invalid + '409': + description: an existing item already exists + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: SKU bundle to be added + in: body + name: bundle + schema: + $ref: '#/definitions/SkuBundle' + /sku/bundle/{id}: + get: + tags: + - bundleManagement + consumes: + - application/json + produces: + - application/json + summary: Get specific sku bundle + operationId: getSkuBundle + description: get sku bundle with given id + responses: + '200': + description: sku bundle returned + schema: + $ref: "#/definitions/SkuBundle" + '404': + description: sku bundle with id not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of sku bundle to be obtained + in: path + name: id + required: true + type: string + put: + tags: + - bundleManagement + consumes: + - application/json + produces: + - application/json + summary: Update specific sku bundle + operationId: updateSkuBundle + description: Update sku bundle with given id + responses: + '200': + description: updated sku bundle + schema: + $ref: "#/definitions/SkuBundle" + '404': + description: sku bundle with id not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of sku bundle to be obtained + in: path + name: id + required: true + type: string + - description: updated sku bundle containing all parameters except id + in: body + name: bundle + required: true + schema: + $ref: "#/definitions/SkuBundle" + /sku/bundle/name/{name}: + get: + tags: + - bundleManagement + consumes: + - application/json + produces: + - application/json + summary: Get specific sku bundle + operationId: getSkuBundleByName + description: get sku bundle with given name + responses: + '200': + description: sku bundle returned + schema: + $ref: "#/definitions/SkuBundle" + '404': + description: sku bundle with name not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of sku bundle to be obtained + in: path + name: name + required: true + type: string + + /sku/price: + get: + tags: + - priceManagement + summary: list SKU Prices + operationId: listSkuPrices + description: lists all sku prices + responses: + '200': + description: list of skus prices returned + schema: + type: array + items: + $ref: "#/definitions/SkuPrice" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + post: + tags: + - priceManagement + consumes: + - application/json + produces: + - application/json + summary: create SKU price + operationId: createSkuPrice + description: Creates a new sku price + responses: + '201': + description: item created + schema: + $ref: "#/definitions/ItemCreatedResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + '400': + description: invalid input, object invalid + '409': + description: an existing item already exists + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: SKU price to be added + in: body + name: price + schema: + $ref: '#/definitions/SkuPrice' + /sku/price/{id}: + get: + tags: + - priceManagement + consumes: + - application/json + produces: + - application/json + summary: Get specific sku price + operationId: getSkuPrice + description: get sku price with given skupriceid + responses: + '200': + description: sku price returned + schema: + $ref: "#/definitions/SkuPrice" + '404': + description: sku price with skupriceid not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of sku price to be obtained + in: path + name: id + required: true + type: string + put: + tags: + - priceManagement + consumes: + - application/json + produces: + - application/json + summary: Update specific sku price + operationId: updateSkuPrice + description: Update sku price with given skupriceid + responses: + '200': + description: updated sku price + schema: + $ref: "#/definitions/SkuPrice" + '404': + description: sku price with skupriceid not found + schema: + $ref: "#/definitions/ErrorResponse" + '500': + description: unexpected error + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - description: Id of sku price to be obtained + in: path + name: id + required: true + type: string + - description: updated sku containing all parameters except id + in: body + name: price + required: true + schema: + $ref: "#/definitions/SkuPrice" + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + ItemCreatedResponse: + properties: + Link: + type: string + ID: + type: string + Message: + type: string + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + Metadata: + type: object + x-go-type: + import: + package: "gitlab.com/cyclops-enterprise/datamodels" + type: JSONdb + + Cycle: + type: object + required: + - State + - ResourceType + - SkuList + properties: + ID: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + State: + type: string + ResourceType: + type: string + SkuList: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + + Plan: + type: object + required: + - Name + - OfferedEndDate + - OfferedStartDate + properties: + Discount: + type: number + format: double + default: 0.0 + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + ID: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + Name: + type: string + example: 'Standard 3 year plan starting 1/1/2019' + OfferedEndDate: + type: string + format: date + example: '2016-08-29' + x-go-custom-tag: gorm:"type:date" + OfferedStartDate: + type: string + format: date + example: '2016-08-29' + x-go-custom-tag: gorm:"type:date" + SkuPrices: + type: array + items: + $ref: "#/definitions/SkuPrice" + x-go-custom-tag: gorm:"-" + + Sku: + type: object + required: + - Name + properties: + ID: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + Name: + type: string + example: 'Standard 3 year plan starting 1/1/2019' + Unit: + type: string + + SkuBundle: + type: object + required: + - Name + properties: + ID: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + Name: + type: string + SkuPrices: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + + SkuPrice: + type: object + required: + - PlanID + - SkuID + - Unit + - UnitPrice + properties: + ID: + type: string + x-go-custom-tag: gorm:"primary_key;unique;default:md5(random()::text || clock_timestamp()::text)::uuid" + PlanID: + type: string + Discount: + type: number + format: double + default: 0.0 + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + SkuID: + type: string + SkuName: + type: string + Unit: + type: string + UnitPrice: + type: number + format: double + x-go-custom-tag: gorm:"type:numeric(23,13)" + UnitCreditPrice: + type: number + format: double + x-go-custom-tag: gorm:"type:numeric(23,13)" + AccountingMode: + type: string + x-go-custom-tag: gorm:"index;default:CREDIT" + default: CREDIT + enum: + - CREDIT + - CASH + - BOTH + - NONE diff --git a/services/udr/README.md b/services/udr/README.md new file mode 100644 index 0000000..0bf6f65 --- /dev/null +++ b/services/udr/README.md @@ -0,0 +1,26 @@ +# USAGE DATA REPORT SERVICE + +Cyclops Engine's Usage Data Report Service implemented in Go + +## How to build + +The building of the service is carried by a multistage docker build, we build everything in an image containing everything needed to build Golang applications and then the executable is moved to a new image that contains the bare minimum starting from the scratch image. + +Within the folder build at the root of the repo there's a script call start.sh, it's invokation admits "Dev" as parameter. Running the script with the parameter will use the local version in the repository as the base for the building of the service's docker image, however doing it without providing it will make the building of the service taking everything from sources. + +``` +./start.sh [Dev] +``` + +The initial branch used when building from sources is "master", it can be changed with a few other parameters by editing the script. + +Using the [Dev] optional argument will take the code present in the repo at the moment of invokation. + +## How to run + +Within the folder run at the root of the repo there's a docker-compose sample file and a config.toml sample file. Once configured with appropriate data to start the service just issue the following command: + +``` +docker-compose up -d +``` + diff --git a/services/udr/client/metrics_management/get_metrics_parameters.go b/services/udr/client/metrics_management/get_metrics_parameters.go new file mode 100644 index 0000000..25c42ba --- /dev/null +++ b/services/udr/client/metrics_management/get_metrics_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetMetricsParams creates a new GetMetricsParams object +// with the default values initialized. +func NewGetMetricsParams() *GetMetricsParams { + + return &GetMetricsParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetMetricsParamsWithTimeout creates a new GetMetricsParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetMetricsParamsWithTimeout(timeout time.Duration) *GetMetricsParams { + + return &GetMetricsParams{ + + timeout: timeout, + } +} + +// NewGetMetricsParamsWithContext creates a new GetMetricsParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetMetricsParamsWithContext(ctx context.Context) *GetMetricsParams { + + return &GetMetricsParams{ + + Context: ctx, + } +} + +// NewGetMetricsParamsWithHTTPClient creates a new GetMetricsParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetMetricsParamsWithHTTPClient(client *http.Client) *GetMetricsParams { + + return &GetMetricsParams{ + HTTPClient: client, + } +} + +/*GetMetricsParams contains all the parameters to send to the API endpoint +for the get metrics operation typically these are written to a http.Request +*/ +type GetMetricsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get metrics params +func (o *GetMetricsParams) WithTimeout(timeout time.Duration) *GetMetricsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get metrics params +func (o *GetMetricsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get metrics params +func (o *GetMetricsParams) WithContext(ctx context.Context) *GetMetricsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get metrics params +func (o *GetMetricsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get metrics params +func (o *GetMetricsParams) WithHTTPClient(client *http.Client) *GetMetricsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get metrics params +func (o *GetMetricsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetMetricsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/client/metrics_management/get_metrics_responses.go b/services/udr/client/metrics_management/get_metrics_responses.go new file mode 100644 index 0000000..5cf5dcd --- /dev/null +++ b/services/udr/client/metrics_management/get_metrics_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetMetricsReader is a Reader for the GetMetrics structure. +type GetMetricsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetMetricsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetMetricsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewGetMetricsInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetMetricsOK creates a GetMetricsOK with default headers values +func NewGetMetricsOK() *GetMetricsOK { + return &GetMetricsOK{} +} + +/*GetMetricsOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetMetricsOK struct { + Payload []*models.Metric +} + +func (o *GetMetricsOK) Error() string { + return fmt.Sprintf("[GET /metrics][%d] getMetricsOK %+v", 200, o.Payload) +} + +func (o *GetMetricsOK) GetPayload() []*models.Metric { + return o.Payload +} + +func (o *GetMetricsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetMetricsInternalServerError creates a GetMetricsInternalServerError with default headers values +func NewGetMetricsInternalServerError() *GetMetricsInternalServerError { + return &GetMetricsInternalServerError{} +} + +/*GetMetricsInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetMetricsInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetMetricsInternalServerError) Error() string { + return fmt.Sprintf("[GET /metrics][%d] getMetricsInternalServerError %+v", 500, o.Payload) +} + +func (o *GetMetricsInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetMetricsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/udr/client/metrics_management/metrics_management_client.go b/services/udr/client/metrics_management/metrics_management_client.go new file mode 100644 index 0000000..a550455 --- /dev/null +++ b/services/udr/client/metrics_management/metrics_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the metrics management client +type API interface { + /* + GetMetrics lists of all metric types processed by the service*/ + GetMetrics(ctx context.Context, params *GetMetricsParams) (*GetMetricsOK, error) +} + +// New creates a new metrics management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for metrics management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetMetrics lists of all metric types processed by the service +*/ +func (a *Client) GetMetrics(ctx context.Context, params *GetMetricsParams) (*GetMetricsOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getMetrics", + Method: "GET", + PathPattern: "/metrics", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetMetricsReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetMetricsOK), nil + +} diff --git a/services/udr/client/status_management/get_status_parameters.go b/services/udr/client/status_management/get_status_parameters.go new file mode 100644 index 0000000..bc38256 --- /dev/null +++ b/services/udr/client/status_management/get_status_parameters.go @@ -0,0 +1,135 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetStatusParams creates a new GetStatusParams object +// with the default values initialized. +func NewGetStatusParams() *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetStatusParamsWithTimeout creates a new GetStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams { + var () + return &GetStatusParams{ + + timeout: timeout, + } +} + +// NewGetStatusParamsWithContext creates a new GetStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams { + var () + return &GetStatusParams{ + + Context: ctx, + } +} + +// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams { + var () + return &GetStatusParams{ + HTTPClient: client, + } +} + +/*GetStatusParams contains all the parameters to send to the API endpoint +for the get status operation typically these are written to a http.Request +*/ +type GetStatusParams struct { + + /*ID + Id of the endpoint to be checked + + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get status params +func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get status params +func (o *GetStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get status params +func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get status params +func (o *GetStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get status params +func (o *GetStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get status params +func (o *GetStatusParams) WithID(id string) *GetStatusParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get status params +func (o *GetStatusParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/client/status_management/get_status_responses.go b/services/udr/client/status_management/get_status_responses.go new file mode 100644 index 0000000..f6f8377 --- /dev/null +++ b/services/udr/client/status_management/get_status_responses.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetStatusReader is a Reader for the GetStatus structure. +type GetStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 404: + result := NewGetStatusNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetStatusOK creates a GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + return &GetStatusOK{} +} + +/*GetStatusOK handles this case with default header values. + +Status information of the system +*/ +type GetStatusOK struct { + Payload *models.Status +} + +func (o *GetStatusOK) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusOK %+v", 200, o.Payload) +} + +func (o *GetStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetStatusNotFound creates a GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + return &GetStatusNotFound{} +} + +/*GetStatusNotFound handles this case with default header values. + +The endpoint provided doesn't exist +*/ +type GetStatusNotFound struct { + Payload *models.ErrorResponse +} + +func (o *GetStatusNotFound) Error() string { + return fmt.Sprintf("[GET /status/{id}][%d] getStatusNotFound %+v", 404, o.Payload) +} + +func (o *GetStatusNotFound) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetStatusNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/udr/client/status_management/show_status_parameters.go b/services/udr/client/status_management/show_status_parameters.go new file mode 100644 index 0000000..e17131c --- /dev/null +++ b/services/udr/client/status_management/show_status_parameters.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// with the default values initialized. +func NewShowStatusParams() *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewShowStatusParamsWithTimeout creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewShowStatusParamsWithTimeout(timeout time.Duration) *ShowStatusParams { + + return &ShowStatusParams{ + + timeout: timeout, + } +} + +// NewShowStatusParamsWithContext creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a context for a request +func NewShowStatusParamsWithContext(ctx context.Context) *ShowStatusParams { + + return &ShowStatusParams{ + + Context: ctx, + } +} + +// NewShowStatusParamsWithHTTPClient creates a new ShowStatusParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewShowStatusParamsWithHTTPClient(client *http.Client) *ShowStatusParams { + + return &ShowStatusParams{ + HTTPClient: client, + } +} + +/*ShowStatusParams contains all the parameters to send to the API endpoint +for the show status operation typically these are written to a http.Request +*/ +type ShowStatusParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the show status params +func (o *ShowStatusParams) WithTimeout(timeout time.Duration) *ShowStatusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the show status params +func (o *ShowStatusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the show status params +func (o *ShowStatusParams) WithContext(ctx context.Context) *ShowStatusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the show status params +func (o *ShowStatusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) WithHTTPClient(client *http.Client) *ShowStatusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the show status params +func (o *ShowStatusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *ShowStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/client/status_management/show_status_responses.go b/services/udr/client/status_management/show_status_responses.go new file mode 100644 index 0000000..88137e6 --- /dev/null +++ b/services/udr/client/status_management/show_status_responses.go @@ -0,0 +1,69 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// ShowStatusReader is a Reader for the ShowStatus structure. +type ShowStatusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ShowStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewShowStatusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewShowStatusOK creates a ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + return &ShowStatusOK{} +} + +/*ShowStatusOK handles this case with default header values. + +Status information of the system +*/ +type ShowStatusOK struct { + Payload *models.Status +} + +func (o *ShowStatusOK) Error() string { + return fmt.Sprintf("[GET /status][%d] showStatusOK %+v", 200, o.Payload) +} + +func (o *ShowStatusOK) GetPayload() *models.Status { + return o.Payload +} + +func (o *ShowStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.Status) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/udr/client/status_management/status_management_client.go b/services/udr/client/status_management/status_management_client.go new file mode 100644 index 0000000..1267c48 --- /dev/null +++ b/services/udr/client/status_management/status_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the status management client +type API interface { + /* + GetStatus basics status of the system*/ + GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) + /* + ShowStatus basics status of the system*/ + ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) +} + +// New creates a new status management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for status management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetStatus basics status of the system +*/ +func (a *Client) GetStatus(ctx context.Context, params *GetStatusParams) (*GetStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getStatus", + Method: "GET", + PathPattern: "/status/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetStatusOK), nil + +} + +/* +ShowStatus basics status of the system +*/ +func (a *Client) ShowStatus(ctx context.Context, params *ShowStatusParams) (*ShowStatusOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "showStatus", + Method: "GET", + PathPattern: "/status", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ShowStatusReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ShowStatusOK), nil + +} diff --git a/services/udr/client/trigger_management/exec_compactation_parameters.go b/services/udr/client/trigger_management/exec_compactation_parameters.go new file mode 100644 index 0000000..0bd55e5 --- /dev/null +++ b/services/udr/client/trigger_management/exec_compactation_parameters.go @@ -0,0 +1,211 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewExecCompactationParams creates a new ExecCompactationParams object +// with the default values initialized. +func NewExecCompactationParams() *ExecCompactationParams { + var () + return &ExecCompactationParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewExecCompactationParamsWithTimeout creates a new ExecCompactationParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewExecCompactationParamsWithTimeout(timeout time.Duration) *ExecCompactationParams { + var () + return &ExecCompactationParams{ + + timeout: timeout, + } +} + +// NewExecCompactationParamsWithContext creates a new ExecCompactationParams object +// with the default values initialized, and the ability to set a context for a request +func NewExecCompactationParamsWithContext(ctx context.Context) *ExecCompactationParams { + var () + return &ExecCompactationParams{ + + Context: ctx, + } +} + +// NewExecCompactationParamsWithHTTPClient creates a new ExecCompactationParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewExecCompactationParamsWithHTTPClient(client *http.Client) *ExecCompactationParams { + var () + return &ExecCompactationParams{ + HTTPClient: client, + } +} + +/*ExecCompactationParams contains all the parameters to send to the API endpoint +for the exec compactation operation typically these are written to a http.Request +*/ +type ExecCompactationParams struct { + + /*FastMode + Switch for using 15m boundaries instead of 8h + + */ + FastMode *bool + /*From + Datetime from which to get the usage report + + */ + From *strfmt.DateTime + /*To + Datetime until which to get the usage report + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the exec compactation params +func (o *ExecCompactationParams) WithTimeout(timeout time.Duration) *ExecCompactationParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the exec compactation params +func (o *ExecCompactationParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the exec compactation params +func (o *ExecCompactationParams) WithContext(ctx context.Context) *ExecCompactationParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the exec compactation params +func (o *ExecCompactationParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the exec compactation params +func (o *ExecCompactationParams) WithHTTPClient(client *http.Client) *ExecCompactationParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the exec compactation params +func (o *ExecCompactationParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFastMode adds the fastMode to the exec compactation params +func (o *ExecCompactationParams) WithFastMode(fastMode *bool) *ExecCompactationParams { + o.SetFastMode(fastMode) + return o +} + +// SetFastMode adds the fastMode to the exec compactation params +func (o *ExecCompactationParams) SetFastMode(fastMode *bool) { + o.FastMode = fastMode +} + +// WithFrom adds the from to the exec compactation params +func (o *ExecCompactationParams) WithFrom(from *strfmt.DateTime) *ExecCompactationParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the exec compactation params +func (o *ExecCompactationParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithTo adds the to to the exec compactation params +func (o *ExecCompactationParams) WithTo(to *strfmt.DateTime) *ExecCompactationParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the exec compactation params +func (o *ExecCompactationParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *ExecCompactationParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.FastMode != nil { + + // query param fast_mode + var qrFastMode bool + if o.FastMode != nil { + qrFastMode = *o.FastMode + } + qFastMode := swag.FormatBool(qrFastMode) + if qFastMode != "" { + if err := r.SetQueryParam("fast_mode", qFastMode); err != nil { + return err + } + } + + } + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/client/trigger_management/exec_compactation_responses.go b/services/udr/client/trigger_management/exec_compactation_responses.go new file mode 100644 index 0000000..bdd7188 --- /dev/null +++ b/services/udr/client/trigger_management/exec_compactation_responses.go @@ -0,0 +1,96 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// ExecCompactationReader is a Reader for the ExecCompactation structure. +type ExecCompactationReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *ExecCompactationReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewExecCompactationOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewExecCompactationInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewExecCompactationOK creates a ExecCompactationOK with default headers values +func NewExecCompactationOK() *ExecCompactationOK { + return &ExecCompactationOK{} +} + +/*ExecCompactationOK handles this case with default header values. + +Compactation task executed successfully. +*/ +type ExecCompactationOK struct { +} + +func (o *ExecCompactationOK) Error() string { + return fmt.Sprintf("[GET /trigger/compact][%d] execCompactationOK ", 200) +} + +func (o *ExecCompactationOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + +// NewExecCompactationInternalServerError creates a ExecCompactationInternalServerError with default headers values +func NewExecCompactationInternalServerError() *ExecCompactationInternalServerError { + return &ExecCompactationInternalServerError{} +} + +/*ExecCompactationInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type ExecCompactationInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *ExecCompactationInternalServerError) Error() string { + return fmt.Sprintf("[GET /trigger/compact][%d] execCompactationInternalServerError %+v", 500, o.Payload) +} + +func (o *ExecCompactationInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *ExecCompactationInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/udr/client/trigger_management/trigger_management_client.go b/services/udr/client/trigger_management/trigger_management_client.go new file mode 100644 index 0000000..b4aa446 --- /dev/null +++ b/services/udr/client/trigger_management/trigger_management_client.go @@ -0,0 +1,66 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the trigger management client +type API interface { + /* + ExecCompactation compactations task trigger*/ + ExecCompactation(ctx context.Context, params *ExecCompactationParams) (*ExecCompactationOK, error) +} + +// New creates a new trigger management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for trigger management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +ExecCompactation compactations task trigger +*/ +func (a *Client) ExecCompactation(ctx context.Context, params *ExecCompactationParams) (*ExecCompactationOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "execCompactation", + Method: "GET", + PathPattern: "/trigger/compact", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &ExecCompactationReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*ExecCompactationOK), nil + +} diff --git a/services/udr/client/u_d_r_management_api_client.go b/services/udr/client/u_d_r_management_api_client.go new file mode 100644 index 0000000..a3ec439 --- /dev/null +++ b/services/udr/client/u_d_r_management_api_client.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + "net/url" + + "github.com/go-openapi/runtime" + rtclient "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client/metrics_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/client/usage_management" +) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost:8000" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/api/v1.0" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"http", "https"} + +type Config struct { + // URL is the base URL of the upstream server + URL *url.URL + // Transport is an inner transport for the client + Transport http.RoundTripper + // AuthInfo is for authentication + AuthInfo runtime.ClientAuthInfoWriter +} + +// New creates a new u d r management API HTTP client. +func New(c Config) *UDRManagementAPI { + var ( + host = DefaultHost + basePath = DefaultBasePath + schemes = DefaultSchemes + ) + + if c.URL != nil { + host = c.URL.Host + basePath = c.URL.Path + schemes = []string{c.URL.Scheme} + } + + transport := rtclient.New(host, basePath, schemes) + if c.Transport != nil { + transport.Transport = c.Transport + } + + cli := new(UDRManagementAPI) + cli.Transport = transport + cli.MetricsManagement = metrics_management.New(transport, strfmt.Default, c.AuthInfo) + cli.StatusManagement = status_management.New(transport, strfmt.Default, c.AuthInfo) + cli.TriggerManagement = trigger_management.New(transport, strfmt.Default, c.AuthInfo) + cli.UsageManagement = usage_management.New(transport, strfmt.Default, c.AuthInfo) + return cli +} + +// UDRManagementAPI is a client for u d r management API +type UDRManagementAPI struct { + MetricsManagement *metrics_management.Client + StatusManagement *status_management.Client + TriggerManagement *trigger_management.Client + UsageManagement *usage_management.Client + Transport runtime.ClientTransport +} diff --git a/services/udr/client/usage_management/get_system_usage_parameters.go b/services/udr/client/usage_management/get_system_usage_parameters.go new file mode 100644 index 0000000..2be27ed --- /dev/null +++ b/services/udr/client/usage_management/get_system_usage_parameters.go @@ -0,0 +1,242 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSystemUsageParams creates a new GetSystemUsageParams object +// with the default values initialized. +func NewGetSystemUsageParams() *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetSystemUsageParamsWithTimeout creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetSystemUsageParamsWithTimeout(timeout time.Duration) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + timeout: timeout, + } +} + +// NewGetSystemUsageParamsWithContext creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetSystemUsageParamsWithContext(ctx context.Context) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + + Context: ctx, + } +} + +// NewGetSystemUsageParamsWithHTTPClient creates a new GetSystemUsageParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetSystemUsageParamsWithHTTPClient(client *http.Client) *GetSystemUsageParams { + var () + return &GetSystemUsageParams{ + HTTPClient: client, + } +} + +/*GetSystemUsageParams contains all the parameters to send to the API endpoint +for the get system usage operation typically these are written to a http.Request +*/ +type GetSystemUsageParams struct { + + /*From + Datetime from which to get the usage report + + */ + From *strfmt.DateTime + /*Idlist + List of ids to be queried + + */ + Idlist *string + /*Metric + Metric(s) to get the usage report + + */ + Metric *string + /*To + Datetime until which to get the usage report + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get system usage params +func (o *GetSystemUsageParams) WithTimeout(timeout time.Duration) *GetSystemUsageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get system usage params +func (o *GetSystemUsageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get system usage params +func (o *GetSystemUsageParams) WithContext(ctx context.Context) *GetSystemUsageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get system usage params +func (o *GetSystemUsageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get system usage params +func (o *GetSystemUsageParams) WithHTTPClient(client *http.Client) *GetSystemUsageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get system usage params +func (o *GetSystemUsageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get system usage params +func (o *GetSystemUsageParams) WithFrom(from *strfmt.DateTime) *GetSystemUsageParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get system usage params +func (o *GetSystemUsageParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithIdlist adds the idlist to the get system usage params +func (o *GetSystemUsageParams) WithIdlist(idlist *string) *GetSystemUsageParams { + o.SetIdlist(idlist) + return o +} + +// SetIdlist adds the idlist to the get system usage params +func (o *GetSystemUsageParams) SetIdlist(idlist *string) { + o.Idlist = idlist +} + +// WithMetric adds the metric to the get system usage params +func (o *GetSystemUsageParams) WithMetric(metric *string) *GetSystemUsageParams { + o.SetMetric(metric) + return o +} + +// SetMetric adds the metric to the get system usage params +func (o *GetSystemUsageParams) SetMetric(metric *string) { + o.Metric = metric +} + +// WithTo adds the to to the get system usage params +func (o *GetSystemUsageParams) WithTo(to *strfmt.DateTime) *GetSystemUsageParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get system usage params +func (o *GetSystemUsageParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSystemUsageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + if o.Idlist != nil { + + // query param idlist + var qrIdlist string + if o.Idlist != nil { + qrIdlist = *o.Idlist + } + qIdlist := qrIdlist + if qIdlist != "" { + if err := r.SetQueryParam("idlist", qIdlist); err != nil { + return err + } + } + + } + + if o.Metric != nil { + + // query param metric + var qrMetric string + if o.Metric != nil { + qrMetric = *o.Metric + } + qMetric := qrMetric + if qMetric != "" { + if err := r.SetQueryParam("metric", qMetric); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/client/usage_management/get_system_usage_responses.go b/services/udr/client/usage_management/get_system_usage_responses.go new file mode 100644 index 0000000..0d1e36c --- /dev/null +++ b/services/udr/client/usage_management/get_system_usage_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetSystemUsageReader is a Reader for the GetSystemUsage structure. +type GetSystemUsageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSystemUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSystemUsageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewGetSystemUsageInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetSystemUsageOK creates a GetSystemUsageOK with default headers values +func NewGetSystemUsageOK() *GetSystemUsageOK { + return &GetSystemUsageOK{} +} + +/*GetSystemUsageOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetSystemUsageOK struct { + Payload []*models.UReport +} + +func (o *GetSystemUsageOK) Error() string { + return fmt.Sprintf("[GET /usage][%d] getSystemUsageOK %+v", 200, o.Payload) +} + +func (o *GetSystemUsageOK) GetPayload() []*models.UReport { + return o.Payload +} + +func (o *GetSystemUsageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSystemUsageInternalServerError creates a GetSystemUsageInternalServerError with default headers values +func NewGetSystemUsageInternalServerError() *GetSystemUsageInternalServerError { + return &GetSystemUsageInternalServerError{} +} + +/*GetSystemUsageInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetSystemUsageInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetSystemUsageInternalServerError) Error() string { + return fmt.Sprintf("[GET /usage][%d] getSystemUsageInternalServerError %+v", 500, o.Payload) +} + +func (o *GetSystemUsageInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetSystemUsageInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/udr/client/usage_management/get_usage_parameters.go b/services/udr/client/usage_management/get_usage_parameters.go new file mode 100644 index 0000000..a070629 --- /dev/null +++ b/services/udr/client/usage_management/get_usage_parameters.go @@ -0,0 +1,231 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetUsageParams creates a new GetUsageParams object +// with the default values initialized. +func NewGetUsageParams() *GetUsageParams { + var () + return &GetUsageParams{ + + timeout: cr.DefaultTimeout, + } +} + +// NewGetUsageParamsWithTimeout creates a new GetUsageParams object +// with the default values initialized, and the ability to set a timeout on a request +func NewGetUsageParamsWithTimeout(timeout time.Duration) *GetUsageParams { + var () + return &GetUsageParams{ + + timeout: timeout, + } +} + +// NewGetUsageParamsWithContext creates a new GetUsageParams object +// with the default values initialized, and the ability to set a context for a request +func NewGetUsageParamsWithContext(ctx context.Context) *GetUsageParams { + var () + return &GetUsageParams{ + + Context: ctx, + } +} + +// NewGetUsageParamsWithHTTPClient creates a new GetUsageParams object +// with the default values initialized, and the ability to set a custom HTTPClient for a request +func NewGetUsageParamsWithHTTPClient(client *http.Client) *GetUsageParams { + var () + return &GetUsageParams{ + HTTPClient: client, + } +} + +/*GetUsageParams contains all the parameters to send to the API endpoint +for the get usage operation typically these are written to a http.Request +*/ +type GetUsageParams struct { + + /*From + Datetime from which to get the usage report + + */ + From *strfmt.DateTime + /*ID + Id of the account to be checked + + */ + ID string + /*Metric + Metric(s) to get the usage report + + */ + Metric *string + /*To + Datetime until which to get the usage report + + */ + To *strfmt.DateTime + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithTimeout adds the timeout to the get usage params +func (o *GetUsageParams) WithTimeout(timeout time.Duration) *GetUsageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get usage params +func (o *GetUsageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get usage params +func (o *GetUsageParams) WithContext(ctx context.Context) *GetUsageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get usage params +func (o *GetUsageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get usage params +func (o *GetUsageParams) WithHTTPClient(client *http.Client) *GetUsageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get usage params +func (o *GetUsageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get usage params +func (o *GetUsageParams) WithFrom(from *strfmt.DateTime) *GetUsageParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get usage params +func (o *GetUsageParams) SetFrom(from *strfmt.DateTime) { + o.From = from +} + +// WithID adds the id to the get usage params +func (o *GetUsageParams) WithID(id string) *GetUsageParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get usage params +func (o *GetUsageParams) SetID(id string) { + o.ID = id +} + +// WithMetric adds the metric to the get usage params +func (o *GetUsageParams) WithMetric(metric *string) *GetUsageParams { + o.SetMetric(metric) + return o +} + +// SetMetric adds the metric to the get usage params +func (o *GetUsageParams) SetMetric(metric *string) { + o.Metric = metric +} + +// WithTo adds the to to the get usage params +func (o *GetUsageParams) WithTo(to *strfmt.DateTime) *GetUsageParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get usage params +func (o *GetUsageParams) SetTo(to *strfmt.DateTime) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetUsageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom strfmt.DateTime + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom.String() + if qFrom != "" { + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if o.Metric != nil { + + // query param metric + var qrMetric string + if o.Metric != nil { + qrMetric = *o.Metric + } + qMetric := qrMetric + if qMetric != "" { + if err := r.SetQueryParam("metric", qMetric); err != nil { + return err + } + } + + } + + if o.To != nil { + + // query param to + var qrTo strfmt.DateTime + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo.String() + if qTo != "" { + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/client/usage_management/get_usage_responses.go b/services/udr/client/usage_management/get_usage_responses.go new file mode 100644 index 0000000..16a050c --- /dev/null +++ b/services/udr/client/usage_management/get_usage_responses.go @@ -0,0 +1,106 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetUsageReader is a Reader for the GetUsage structure. +type GetUsageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetUsageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetUsageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 500: + result := NewGetUsageInternalServerError() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + + default: + return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) + } +} + +// NewGetUsageOK creates a GetUsageOK with default headers values +func NewGetUsageOK() *GetUsageOK { + return &GetUsageOK{} +} + +/*GetUsageOK handles this case with default header values. + +Description of a successfully operation +*/ +type GetUsageOK struct { + Payload []*models.UReport +} + +func (o *GetUsageOK) Error() string { + return fmt.Sprintf("[GET /usage/{id}][%d] getUsageOK %+v", 200, o.Payload) +} + +func (o *GetUsageOK) GetPayload() []*models.UReport { + return o.Payload +} + +func (o *GetUsageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetUsageInternalServerError creates a GetUsageInternalServerError with default headers values +func NewGetUsageInternalServerError() *GetUsageInternalServerError { + return &GetUsageInternalServerError{} +} + +/*GetUsageInternalServerError handles this case with default header values. + +Something unexpected happend, error raised +*/ +type GetUsageInternalServerError struct { + Payload *models.ErrorResponse +} + +func (o *GetUsageInternalServerError) Error() string { + return fmt.Sprintf("[GET /usage/{id}][%d] getUsageInternalServerError %+v", 500, o.Payload) +} + +func (o *GetUsageInternalServerError) GetPayload() *models.ErrorResponse { + return o.Payload +} + +func (o *GetUsageInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.ErrorResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/services/udr/client/usage_management/usage_management_client.go b/services/udr/client/usage_management/usage_management_client.go new file mode 100644 index 0000000..8706d3f --- /dev/null +++ b/services/udr/client/usage_management/usage_management_client.go @@ -0,0 +1,94 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/runtime" + + strfmt "github.com/go-openapi/strfmt" +) + +//go:generate mockery -name API -inpkg + +// API is the interface of the usage management client +type API interface { + /* + GetSystemUsage detaileds report covering all accounts within the specified time window*/ + GetSystemUsage(ctx context.Context, params *GetSystemUsageParams) (*GetSystemUsageOK, error) + /* + GetUsage detaileds report covering of the account associated with the id within the specified time window*/ + GetUsage(ctx context.Context, params *GetUsageParams) (*GetUsageOK, error) +} + +// New creates a new usage management API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry, authInfo runtime.ClientAuthInfoWriter) *Client { + return &Client{ + transport: transport, + formats: formats, + authInfo: authInfo, + } +} + +/* +Client for usage management API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry + authInfo runtime.ClientAuthInfoWriter +} + +/* +GetSystemUsage detaileds report covering all accounts within the specified time window +*/ +func (a *Client) GetSystemUsage(ctx context.Context, params *GetSystemUsageParams) (*GetSystemUsageOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getSystemUsage", + Method: "GET", + PathPattern: "/usage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetSystemUsageReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetSystemUsageOK), nil + +} + +/* +GetUsage detaileds report covering of the account associated with the id within the specified time window +*/ +func (a *Client) GetUsage(ctx context.Context, params *GetUsageParams) (*GetUsageOK, error) { + + result, err := a.transport.Submit(&runtime.ClientOperation{ + ID: "getUsage", + Method: "GET", + PathPattern: "/usage/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"http", "https"}, + Params: params, + Reader: &GetUsageReader{formats: a.formats}, + AuthInfo: a.authInfo, + Context: ctx, + Client: params.HTTPClient, + }) + if err != nil { + return nil, err + } + return result.(*GetUsageOK), nil + +} diff --git a/services/udr/go.mod b/services/udr/go.mod new file mode 100644 index 0000000..daff8f8 --- /dev/null +++ b/services/udr/go.mod @@ -0,0 +1,28 @@ +module github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr + +go 1.15 + +require ( + github.com/Nerzal/gocloak/v7 v7.11.0 + github.com/go-openapi/errors v0.20.1 + github.com/go-openapi/loads v0.21.0 + github.com/go-openapi/runtime v0.21.0 + github.com/go-openapi/spec v0.20.4 + github.com/go-openapi/strfmt v0.21.1 + github.com/go-openapi/swag v0.19.15 + github.com/go-openapi/validate v0.20.3 + github.com/prometheus/client_golang v1.11.0 + github.com/remeh/sizedwaitgroup v1.0.0 + github.com/rs/cors v1.8.2 + github.com/segmentio/encoding v0.3.2 + github.com/segmentio/kafka-go v0.4.25 + github.com/spf13/viper v1.10.1 + gitlab.com/cyclops-utilities/datamodels v0.0.0-20191016132854-e9313e683e5b + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine v0.0.1 + github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager v0.0.1 + gitlab.com/cyclops-utilities/logging v0.0.0-20200914110347-ca1d02efd346 + gorm.io/driver/postgres v1.2.3 + gorm.io/gorm v1.22.4 +) diff --git a/services/udr/models/error_response.go b/services/udr/models/error_response.go new file mode 100644 index 0000000..1261fc6 --- /dev/null +++ b/services/udr/models/error_response.go @@ -0,0 +1,64 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// ErrorResponse error response +// +// swagger:model ErrorResponse +type ErrorResponse struct { + + // error string + // Required: true + ErrorString *string `json:"errorString"` +} + +// Validate validates this error response +func (m *ErrorResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorString(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *ErrorResponse) validateErrorString(formats strfmt.Registry) error { + + if err := validate.Required("errorString", "body", m.ErrorString); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *ErrorResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *ErrorResponse) UnmarshalBinary(b []byte) error { + var res ErrorResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/udr/models/metric.go b/services/udr/models/metric.go new file mode 100644 index 0000000..7f6c984 --- /dev/null +++ b/services/udr/models/metric.go @@ -0,0 +1,43 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// Metric metric +// +// swagger:model Metric +type Metric struct { + + // metric + Metric string `json:"Metric,omitempty" gorm:"primary_key"` +} + +// Validate validates this metric +func (m *Metric) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *Metric) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Metric) UnmarshalBinary(b []byte) error { + var res Metric + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/udr/models/status.go b/services/udr/models/status.go new file mode 100644 index 0000000..8f19395 --- /dev/null +++ b/services/udr/models/status.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// Status status +// +// swagger:model Status +type Status struct { + + // average response time + AverageResponseTime float64 `json:"AverageResponseTime,omitempty"` + + // d b state + DBState string `json:"DBState,omitempty"` + + // last request + LastRequest string `json:"LastRequest,omitempty"` + + // requests bo t + RequestsBoT int64 `json:"RequestsBoT,omitempty"` + + // requests last hour + RequestsLastHour int64 `json:"RequestsLastHour,omitempty"` + + // requests today + RequestsToday int64 `json:"RequestsToday,omitempty"` + + // system state + // Required: true + SystemState *string `json:"SystemState"` +} + +// Validate validates this status +func (m *Status) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSystemState(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Status) validateSystemState(formats strfmt.Registry) error { + + if err := validate.Required("SystemState", "body", m.SystemState); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Status) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Status) UnmarshalBinary(b []byte) error { + var res Status + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/udr/models/u_d_r_record.go b/services/udr/models/u_d_r_record.go new file mode 100644 index 0000000..fb13e8f --- /dev/null +++ b/services/udr/models/u_d_r_record.go @@ -0,0 +1,111 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// UDRRecord u d r record +// +// swagger:model UDRRecord +type UDRRecord struct { + + // account Id + AccountID string `json:"AccountId,omitempty" gorm:"index"` + + // metadata + Metadata datamodels.JSONdb `json:"Metadata,omitempty" gorm:"type:jsonb"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // time from + // Format: datetime + TimeFrom strfmt.DateTime `json:"TimeFrom,omitempty" gorm:"index;type:timestamptz"` + + // time to + // Format: datetime + TimeTo strfmt.DateTime `json:"TimeTo,omitempty" gorm:"index;type:timestamptz"` + + // unit + Unit string `json:"Unit,omitempty"` + + // usage breakup + UsageBreakup datamodels.JSONdb `json:"UsageBreakup,omitempty" gorm:"type:jsonb"` +} + +// Validate validates this u d r record +func (m *UDRRecord) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTimeFrom(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimeTo(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UDRRecord) validateTimeFrom(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeFrom) { // not required + return nil + } + + if err := validate.FormatOf("TimeFrom", "body", "datetime", m.TimeFrom.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *UDRRecord) validateTimeTo(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeTo) { // not required + return nil + } + + if err := validate.FormatOf("TimeTo", "body", "datetime", m.TimeTo.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UDRRecord) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UDRRecord) UnmarshalBinary(b []byte) error { + var res UDRRecord + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/udr/models/u_d_r_report.go b/services/udr/models/u_d_r_report.go new file mode 100644 index 0000000..9fa087b --- /dev/null +++ b/services/udr/models/u_d_r_report.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "gitlab.com/cyclops-utilities/datamodels" +) + +// UDRReport u d r report +// +// swagger:model UDRReport +type UDRReport struct { + + // metadata + Metadata datamodels.JSONdb `json:"Metadata,omitempty" gorm:"type:jsonb"` + + // resource Id + ResourceID string `json:"ResourceId,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // unit + Unit string `json:"Unit,omitempty"` + + // usage breakup + UsageBreakup datamodels.JSONdb `json:"UsageBreakup,omitempty" gorm:"type:jsonb"` +} + +// Validate validates this u d r report +func (m *UDRReport) Validate(formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UDRReport) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UDRReport) UnmarshalBinary(b []byte) error { + var res UDRReport + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/udr/models/u_report.go b/services/udr/models/u_report.go new file mode 100644 index 0000000..5b06188 --- /dev/null +++ b/services/udr/models/u_report.go @@ -0,0 +1,126 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UReport u report +// +// swagger:model UReport +type UReport struct { + + // account Id + AccountID string `json:"AccountId,omitempty" gorm:"index"` + + // time from + // Format: datetime + TimeFrom strfmt.DateTime `json:"TimeFrom,omitempty" gorm:"index;type:timestamptz"` + + // time to + // Format: datetime + TimeTo strfmt.DateTime `json:"TimeTo,omitempty" gorm:"index;type:timestamptz"` + + // usage + Usage []*UDRReport `json:"Usage" gorm:"-"` +} + +// Validate validates this u report +func (m *UReport) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTimeFrom(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimeTo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUsage(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UReport) validateTimeFrom(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeFrom) { // not required + return nil + } + + if err := validate.FormatOf("TimeFrom", "body", "datetime", m.TimeFrom.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *UReport) validateTimeTo(formats strfmt.Registry) error { + + if swag.IsZero(m.TimeTo) { // not required + return nil + } + + if err := validate.FormatOf("TimeTo", "body", "datetime", m.TimeTo.String(), formats); err != nil { + return err + } + + return nil +} + +func (m *UReport) validateUsage(formats strfmt.Registry) error { + + if swag.IsZero(m.Usage) { // not required + return nil + } + + for i := 0; i < len(m.Usage); i++ { + if swag.IsZero(m.Usage[i]) { // not required + continue + } + + if m.Usage[i] != nil { + if err := m.Usage[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("Usage" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *UReport) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UReport) UnmarshalBinary(b []byte) error { + var res UReport + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/udr/models/usage.go b/services/udr/models/usage.go new file mode 100644 index 0000000..d75d8b1 --- /dev/null +++ b/services/udr/models/usage.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + "gitlab.com/cyclops-utilities/datamodels" +) + +// Usage usage +// +// swagger:model Usage +type Usage struct { + + // account + Account string `json:"Account,omitempty" gorm:"index"` + + // metadata + Metadata datamodels.JSONdb `json:"Metadata,omitempty" gorm:"type:jsonb"` + + // resource ID + ResourceID string `json:"ResourceID,omitempty"` + + // resource name + ResourceName string `json:"ResourceName,omitempty"` + + // resource type + ResourceType string `json:"ResourceType,omitempty"` + + // time + Time int64 `json:"Time,omitempty"` + + // timedate + // Format: datetime + Timedate strfmt.DateTime `json:"Timedate,omitempty" gorm:"index;type:timestamptz"` + + // unit + Unit string `json:"Unit,omitempty"` + + // usage + Usage float64 `json:"Usage,omitempty" gorm:"type:numeric(23,13);default:0.0"` +} + +// Validate validates this usage +func (m *Usage) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTimedate(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *Usage) validateTimedate(formats strfmt.Registry) error { + + if swag.IsZero(m.Timedate) { // not required + return nil + } + + if err := validate.FormatOf("Timedate", "body", "datetime", m.Timedate.String(), formats); err != nil { + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (m *Usage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *Usage) UnmarshalBinary(b []byte) error { + var res Usage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/services/udr/restapi/configure_u_d_r_management_api.go b/services/udr/restapi/configure_u_d_r_management_api.go new file mode 100644 index 0000000..1cbd7d8 --- /dev/null +++ b/services/udr/restapi/configure_u_d_r_management_api.go @@ -0,0 +1,203 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/metrics_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/usage_management" +) + +type contextKey string + +const AuthKey contextKey = "Auth" + +//go:generate mockery -name MetricsManagementAPI -inpkg + +/* MetricsManagementAPI */ +type MetricsManagementAPI interface { + /* GetMetrics List of all metric types processed by the service */ + GetMetrics(ctx context.Context, params metrics_management.GetMetricsParams) middleware.Responder +} + +//go:generate mockery -name StatusManagementAPI -inpkg + +/* StatusManagementAPI */ +type StatusManagementAPI interface { + /* GetStatus Basic status of the system */ + GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder + + /* ShowStatus Basic status of the system */ + ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder +} + +//go:generate mockery -name TriggerManagementAPI -inpkg + +/* TriggerManagementAPI */ +type TriggerManagementAPI interface { + /* ExecCompactation Compactation task trigger */ + ExecCompactation(ctx context.Context, params trigger_management.ExecCompactationParams) middleware.Responder +} + +//go:generate mockery -name UsageManagementAPI -inpkg + +/* UsageManagementAPI */ +type UsageManagementAPI interface { + /* GetSystemUsage Detailed report covering all accounts within the specified time window */ + GetSystemUsage(ctx context.Context, params usage_management.GetSystemUsageParams) middleware.Responder + + /* GetUsage Detailed report covering of the account associated with the id within the specified time window */ + GetUsage(ctx context.Context, params usage_management.GetUsageParams) middleware.Responder +} + +// Config is configuration for Handler +type Config struct { + MetricsManagementAPI + StatusManagementAPI + TriggerManagementAPI + UsageManagementAPI + Logger func(string, ...interface{}) + // InnerMiddleware is for the handler executors. These do not apply to the swagger.json document. + // The middleware executes after routing but before authentication, binding and validation + InnerMiddleware func(http.Handler) http.Handler + + // Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions + // and the principal was stored in the context in the "AuthKey" context value. + Authorizer func(*http.Request) error + + // AuthAPIKeyHeader Applies when the "X-API-KEY" header is set + AuthAPIKeyHeader func(token string) (interface{}, error) + + // AuthAPIKeyParam Applies when the "api_key" query is set + AuthAPIKeyParam func(token string) (interface{}, error) + + // AuthKeycloak For OAuth2 authentication + AuthKeycloak func(token string, scopes []string) (interface{}, error) + // Authenticator to use for all APIKey authentication + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // Authenticator to use for all Bearer authentication + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // Authenticator to use for all Basic authentication + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator +} + +// Handler returns an http.Handler given the handler configuration +// It mounts all the business logic implementers in the right routing. +func Handler(c Config) (http.Handler, error) { + h, _, err := HandlerAPI(c) + return h, err +} + +// HandlerAPI returns an http.Handler given the handler configuration +// and the corresponding *UDRManagementAPI instance. +// It mounts all the business logic implementers in the right routing. +func HandlerAPI(c Config) (http.Handler, *operations.UDRManagementAPIAPI, error) { + spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "") + if err != nil { + return nil, nil, fmt.Errorf("analyze swagger: %v", err) + } + api := operations.NewUDRManagementAPIAPI(spec) + api.ServeError = errors.ServeError + api.Logger = c.Logger + + if c.APIKeyAuthenticator != nil { + api.APIKeyAuthenticator = c.APIKeyAuthenticator + } + if c.BasicAuthenticator != nil { + api.BasicAuthenticator = c.BasicAuthenticator + } + if c.BearerAuthenticator != nil { + api.BearerAuthenticator = c.BearerAuthenticator + } + + api.JSONConsumer = runtime.JSONConsumer() + api.JSONProducer = runtime.JSONProducer() + api.APIKeyHeaderAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyHeader == nil { + return token, nil + } + return c.AuthAPIKeyHeader(token) + } + + api.APIKeyParamAuth = func(token string) (interface{}, error) { + if c.AuthAPIKeyParam == nil { + return token, nil + } + return c.AuthAPIKeyParam(token) + } + + api.KeycloakAuth = func(token string, scopes []string) (interface{}, error) { + if c.AuthKeycloak == nil { + return token, nil + } + return c.AuthKeycloak(token, scopes) + } + api.APIAuthorizer = authorizer(c.Authorizer) + api.TriggerManagementExecCompactationHandler = trigger_management.ExecCompactationHandlerFunc(func(params trigger_management.ExecCompactationParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.TriggerManagementAPI.ExecCompactation(ctx, params) + }) + api.MetricsManagementGetMetricsHandler = metrics_management.GetMetricsHandlerFunc(func(params metrics_management.GetMetricsParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.MetricsManagementAPI.GetMetrics(ctx, params) + }) + api.StatusManagementGetStatusHandler = status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.GetStatus(ctx, params) + }) + api.UsageManagementGetSystemUsageHandler = usage_management.GetSystemUsageHandlerFunc(func(params usage_management.GetSystemUsageParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.UsageManagementAPI.GetSystemUsage(ctx, params) + }) + api.UsageManagementGetUsageHandler = usage_management.GetUsageHandlerFunc(func(params usage_management.GetUsageParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.UsageManagementAPI.GetUsage(ctx, params) + }) + api.StatusManagementShowStatusHandler = status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + ctx := params.HTTPRequest.Context() + ctx = storeAuth(ctx, principal) + return c.StatusManagementAPI.ShowStatus(ctx, params) + }) + api.ServerShutdown = func() {} + return api.Serve(c.InnerMiddleware), api, nil +} + +// swaggerCopy copies the swagger json to prevent data races in runtime +func swaggerCopy(orig json.RawMessage) json.RawMessage { + c := make(json.RawMessage, len(orig)) + copy(c, orig) + return c +} + +// authorizer is a helper function to implement the runtime.Authorizer interface. +type authorizer func(*http.Request) error + +func (a authorizer) Authorize(req *http.Request, principal interface{}) error { + if a == nil { + return nil + } + ctx := storeAuth(req.Context(), principal) + return a(req.WithContext(ctx)) +} + +func storeAuth(ctx context.Context, principal interface{}) context.Context { + return context.WithValue(ctx, AuthKey, principal) +} diff --git a/services/udr/restapi/doc.go b/services/udr/restapi/doc.go new file mode 100644 index 0000000..3d47d3f --- /dev/null +++ b/services/udr/restapi/doc.go @@ -0,0 +1,22 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Package restapi UDR Management API +// +// An API which supports creation, deletion, listing etc of UDR +// Schemes: +// http +// https +// Host: localhost:8000 +// BasePath: /api/v1.0 +// Version: 1.0.0 +// License: Apache 2.0 http://www.apache.org/licenses/LICENSE-2.0.html +// Contact: +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// swagger:meta +package restapi diff --git a/services/udr/restapi/embedded_spec.go b/services/udr/restapi/embedded_spec.go new file mode 100644 index 0000000..b400f44 --- /dev/null +++ b/services/udr/restapi/embedded_spec.go @@ -0,0 +1,1214 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" +) + +var ( + // SwaggerJSON embedded version of the swagger document used at generation time + SwaggerJSON json.RawMessage + // FlatSwaggerJSON embedded flattened version of the swagger document used at generation time + FlatSwaggerJSON json.RawMessage +) + +func init() { + SwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of UDR", + "title": "UDR Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/metrics": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "metricsManagement" + ], + "summary": "List of all metric types processed by the service", + "operationId": "getMetrics", + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Metric" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "metrics", + "usage" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/compact": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Compactation task trigger", + "operationId": "execCompactation", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "boolean", + "description": "Switch for using 15m boundaries instead of 8h", + "name": "fast_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Compactation task executed successfully." + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering all accounts within the specified time window", + "operationId": "getSystemUsage", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + }, + { + "type": "string", + "description": "List of ids to be queried", + "name": "idlist", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/UReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering of the account associated with the id within the specified time window", + "operationId": "getUsage", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/UReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Metric": { + "type": "object", + "properties": { + "Metric": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "UDRRecord": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "UDRReport": { + "type": "object", + "properties": { + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "UReport": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Usage": { + "type": "array", + "items": { + "$ref": "#/definitions/UDRReport" + }, + "x-go-custom-tag": "gorm:\"-\"" + } + } + }, + "Usage": { + "type": "object", + "properties": { + "Account": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceID": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Time": { + "type": "integer" + }, + "Timedate": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Unit": { + "type": "string" + }, + "Usage": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the metrics used and controlled by the system", + "name": "metricsManagement" + }, + { + "description": "Actions relating to the usage reporting of the accounts of the system", + "name": "usageManagement" + } + ] +}`)) + FlatSwaggerJSON = json.RawMessage([]byte(`{ + "schemes": [ + "http", + "https" + ], + "swagger": "2.0", + "info": { + "description": "An API which supports creation, deletion, listing etc of UDR", + "title": "UDR Management API", + "contact": { + "email": "diego@cyclops-labs.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.0" + }, + "host": "localhost:8000", + "basePath": "/api/v1.0", + "paths": { + "/metrics": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "metricsManagement" + ], + "summary": "List of all metric types processed by the service", + "operationId": "getMetrics", + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Metric" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/status": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "showStatus", + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + } + } + } + }, + "/status/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "statusManagement" + ], + "summary": "Basic status of the system", + "operationId": "getStatus", + "parameters": [ + { + "enum": [ + "kafka-receiver", + "kafka-sender", + "status", + "trigger", + "metrics", + "usage" + ], + "type": "string", + "description": "Id of the endpoint to be checked", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Status information of the system", + "schema": { + "$ref": "#/definitions/Status" + } + }, + "404": { + "description": "The endpoint provided doesn't exist", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/trigger/compact": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "triggerManagement" + ], + "summary": "Compactation task trigger", + "operationId": "execCompactation", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "boolean", + "description": "Switch for using 15m boundaries instead of 8h", + "name": "fast_mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Compactation task executed successfully." + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering all accounts within the specified time window", + "operationId": "getSystemUsage", + "parameters": [ + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + }, + { + "type": "string", + "description": "List of ids to be queried", + "name": "idlist", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/UReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + }, + "/usage/{id}": { + "get": { + "security": [ + { + "Keycloak": [ + "user" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "produces": [ + "application/json" + ], + "tags": [ + "usageManagement" + ], + "summary": "Detailed report covering of the account associated with the id within the specified time window", + "operationId": "getUsage", + "parameters": [ + { + "type": "string", + "description": "Id of the account to be checked", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime from which to get the usage report", + "name": "from", + "in": "query" + }, + { + "type": "string", + "format": "datetime", + "description": "Datetime until which to get the usage report", + "name": "to", + "in": "query" + }, + { + "type": "string", + "description": "Metric(s) to get the usage report", + "name": "metric", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Description of a successfully operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/UReport" + } + } + }, + "500": { + "description": "Something unexpected happend, error raised", + "schema": { + "$ref": "#/definitions/ErrorResponse" + } + } + } + } + } + }, + "definitions": { + "ErrorResponse": { + "type": "object", + "required": [ + "errorString" + ], + "properties": { + "errorString": { + "type": "string" + } + } + }, + "Metadata": { + "type": "object", + "x-go-type": { + "import": { + "package": "gitlab.com/cyclops-utilities/datamodels" + }, + "type": "JSONdb" + } + }, + "Metric": { + "type": "object", + "properties": { + "Metric": { + "type": "string", + "x-go-custom-tag": "gorm:\"primary_key\"" + } + } + }, + "Status": { + "type": "object", + "required": [ + "SystemState" + ], + "properties": { + "AverageResponseTime": { + "type": "number", + "format": "double" + }, + "DBState": { + "type": "string" + }, + "LastRequest": { + "type": "string" + }, + "RequestsBoT": { + "type": "integer" + }, + "RequestsLastHour": { + "type": "integer" + }, + "RequestsToday": { + "type": "integer" + }, + "SystemState": { + "type": "string" + } + } + }, + "UDRRecord": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "UDRReport": { + "type": "object", + "properties": { + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceId": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Unit": { + "type": "string" + }, + "UsageBreakup": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + } + } + }, + "UReport": { + "type": "object", + "properties": { + "AccountId": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "TimeFrom": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "TimeTo": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Usage": { + "type": "array", + "items": { + "$ref": "#/definitions/UDRReport" + }, + "x-go-custom-tag": "gorm:\"-\"" + } + } + }, + "Usage": { + "type": "object", + "properties": { + "Account": { + "type": "string", + "x-go-custom-tag": "gorm:\"index\"" + }, + "Metadata": { + "x-go-custom-tag": "gorm:\"type:jsonb\"", + "$ref": "#/definitions/Metadata" + }, + "ResourceID": { + "type": "string" + }, + "ResourceName": { + "type": "string" + }, + "ResourceType": { + "type": "string" + }, + "Time": { + "type": "integer" + }, + "Timedate": { + "type": "string", + "format": "datetime", + "x-go-custom-tag": "gorm:\"index;type:timestamptz\"" + }, + "Unit": { + "type": "string" + }, + "Usage": { + "type": "number", + "format": "double", + "default": 0, + "x-go-custom-tag": "gorm:\"type:numeric(23,13);default:0.0\"" + } + } + } + }, + "securityDefinitions": { + "APIKeyHeader": { + "type": "apiKey", + "name": "X-API-KEY", + "in": "header" + }, + "APIKeyParam": { + "type": "apiKey", + "name": "api_key", + "in": "query" + }, + "Keycloak": { + "type": "oauth2", + "flow": "accessCode", + "authorizationUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth", + "tokenUrl": "http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token", + "scopes": { + "admin": "Admin scope", + "user": "User scope" + } + } + }, + "security": [ + { + "Keycloak": [ + "user", + "admin" + ] + }, + { + "APIKeyHeader": [] + }, + { + "APIKeyParam": [] + } + ], + "tags": [ + { + "description": "Actions relating to the reporting of the state of the service", + "name": "statusManagement" + }, + { + "description": "Actions relating to the periodics actions to be triggered in the system", + "name": "triggerManagement" + }, + { + "description": "Actions relating to the metrics used and controlled by the system", + "name": "metricsManagement" + }, + { + "description": "Actions relating to the usage reporting of the accounts of the system", + "name": "usageManagement" + } + ] +}`)) +} diff --git a/services/udr/restapi/operations/metrics_management/get_metrics.go b/services/udr/restapi/operations/metrics_management/get_metrics.go new file mode 100644 index 0000000..e21b59c --- /dev/null +++ b/services/udr/restapi/operations/metrics_management/get_metrics.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetMetricsHandlerFunc turns a function with the right signature into a get metrics handler +type GetMetricsHandlerFunc func(GetMetricsParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetMetricsHandlerFunc) Handle(params GetMetricsParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetMetricsHandler interface for that can handle valid get metrics params +type GetMetricsHandler interface { + Handle(GetMetricsParams, interface{}) middleware.Responder +} + +// NewGetMetrics creates a new http.Handler for the get metrics operation +func NewGetMetrics(ctx *middleware.Context, handler GetMetricsHandler) *GetMetrics { + return &GetMetrics{Context: ctx, Handler: handler} +} + +/*GetMetrics swagger:route GET /metrics metricsManagement getMetrics + +List of all metric types processed by the service + +*/ +type GetMetrics struct { + Context *middleware.Context + Handler GetMetricsHandler +} + +func (o *GetMetrics) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetMetricsParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/udr/restapi/operations/metrics_management/get_metrics_parameters.go b/services/udr/restapi/operations/metrics_management/get_metrics_parameters.go new file mode 100644 index 0000000..8bb5abb --- /dev/null +++ b/services/udr/restapi/operations/metrics_management/get_metrics_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewGetMetricsParams creates a new GetMetricsParams object +// no default values defined in spec. +func NewGetMetricsParams() GetMetricsParams { + + return GetMetricsParams{} +} + +// GetMetricsParams contains all the bound params for the get metrics operation +// typically these are obtained from a http.Request +// +// swagger:parameters getMetrics +type GetMetricsParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetMetricsParams() beforehand. +func (o *GetMetricsParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/restapi/operations/metrics_management/get_metrics_responses.go b/services/udr/restapi/operations/metrics_management/get_metrics_responses.go new file mode 100644 index 0000000..d76b796 --- /dev/null +++ b/services/udr/restapi/operations/metrics_management/get_metrics_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetMetricsOKCode is the HTTP code returned for type GetMetricsOK +const GetMetricsOKCode int = 200 + +/*GetMetricsOK Description of a successfully operation + +swagger:response getMetricsOK +*/ +type GetMetricsOK struct { + + /* + In: Body + */ + Payload []*models.Metric `json:"body,omitempty"` +} + +// NewGetMetricsOK creates GetMetricsOK with default headers values +func NewGetMetricsOK() *GetMetricsOK { + + return &GetMetricsOK{} +} + +// WithPayload adds the payload to the get metrics o k response +func (o *GetMetricsOK) WithPayload(payload []*models.Metric) *GetMetricsOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get metrics o k response +func (o *GetMetricsOK) SetPayload(payload []*models.Metric) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetMetricsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.Metric, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetMetricsInternalServerErrorCode is the HTTP code returned for type GetMetricsInternalServerError +const GetMetricsInternalServerErrorCode int = 500 + +/*GetMetricsInternalServerError Something unexpected happend, error raised + +swagger:response getMetricsInternalServerError +*/ +type GetMetricsInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetMetricsInternalServerError creates GetMetricsInternalServerError with default headers values +func NewGetMetricsInternalServerError() *GetMetricsInternalServerError { + + return &GetMetricsInternalServerError{} +} + +// WithPayload adds the payload to the get metrics internal server error response +func (o *GetMetricsInternalServerError) WithPayload(payload *models.ErrorResponse) *GetMetricsInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get metrics internal server error response +func (o *GetMetricsInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetMetricsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/udr/restapi/operations/metrics_management/get_metrics_urlbuilder.go b/services/udr/restapi/operations/metrics_management/get_metrics_urlbuilder.go new file mode 100644 index 0000000..1bcb403 --- /dev/null +++ b/services/udr/restapi/operations/metrics_management/get_metrics_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package metrics_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// GetMetricsURL generates an URL for the get metrics operation +type GetMetricsURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetMetricsURL) WithBasePath(bp string) *GetMetricsURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetMetricsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetMetricsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/metrics" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetMetricsURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetMetricsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetMetricsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetMetricsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetMetricsURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetMetricsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/udr/restapi/operations/status_management/get_status.go b/services/udr/restapi/operations/status_management/get_status.go new file mode 100644 index 0000000..2ab4b37 --- /dev/null +++ b/services/udr/restapi/operations/status_management/get_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetStatusHandlerFunc turns a function with the right signature into a get status handler +type GetStatusHandlerFunc func(GetStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetStatusHandlerFunc) Handle(params GetStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetStatusHandler interface for that can handle valid get status params +type GetStatusHandler interface { + Handle(GetStatusParams, interface{}) middleware.Responder +} + +// NewGetStatus creates a new http.Handler for the get status operation +func NewGetStatus(ctx *middleware.Context, handler GetStatusHandler) *GetStatus { + return &GetStatus{Context: ctx, Handler: handler} +} + +/*GetStatus swagger:route GET /status/{id} statusManagement getStatus + +Basic status of the system + +*/ +type GetStatus struct { + Context *middleware.Context + Handler GetStatusHandler +} + +func (o *GetStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/udr/restapi/operations/status_management/get_status_parameters.go b/services/udr/restapi/operations/status_management/get_status_parameters.go new file mode 100644 index 0000000..a31c54e --- /dev/null +++ b/services/udr/restapi/operations/status_management/get_status_parameters.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetStatusParams creates a new GetStatusParams object +// no default values defined in spec. +func NewGetStatusParams() GetStatusParams { + + return GetStatusParams{} +} + +// GetStatusParams contains all the bound params for the get status operation +// typically these are obtained from a http.Request +// +// swagger:parameters getStatus +type GetStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Id of the endpoint to be checked + Required: true + In: path + */ + ID string +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetStatusParams() beforehand. +func (o *GetStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetStatusParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + if err := o.validateID(formats); err != nil { + return err + } + + return nil +} + +// validateID carries on validations for parameter ID +func (o *GetStatusParams) validateID(formats strfmt.Registry) error { + + if err := validate.EnumCase("id", "path", o.ID, []interface{}{"kafka-receiver", "kafka-sender", "status", "trigger", "metrics", "usage"}, true); err != nil { + return err + } + + return nil +} diff --git a/services/udr/restapi/operations/status_management/get_status_responses.go b/services/udr/restapi/operations/status_management/get_status_responses.go new file mode 100644 index 0000000..eded3ac --- /dev/null +++ b/services/udr/restapi/operations/status_management/get_status_responses.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetStatusOKCode is the HTTP code returned for type GetStatusOK +const GetStatusOKCode int = 200 + +/*GetStatusOK Status information of the system + +swagger:response getStatusOK +*/ +type GetStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewGetStatusOK creates GetStatusOK with default headers values +func NewGetStatusOK() *GetStatusOK { + + return &GetStatusOK{} +} + +// WithPayload adds the payload to the get status o k response +func (o *GetStatusOK) WithPayload(payload *models.Status) *GetStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status o k response +func (o *GetStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} + +// GetStatusNotFoundCode is the HTTP code returned for type GetStatusNotFound +const GetStatusNotFoundCode int = 404 + +/*GetStatusNotFound The endpoint provided doesn't exist + +swagger:response getStatusNotFound +*/ +type GetStatusNotFound struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetStatusNotFound creates GetStatusNotFound with default headers values +func NewGetStatusNotFound() *GetStatusNotFound { + + return &GetStatusNotFound{} +} + +// WithPayload adds the payload to the get status not found response +func (o *GetStatusNotFound) WithPayload(payload *models.ErrorResponse) *GetStatusNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get status not found response +func (o *GetStatusNotFound) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetStatusNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(404) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/udr/restapi/operations/status_management/get_status_urlbuilder.go b/services/udr/restapi/operations/status_management/get_status_urlbuilder.go new file mode 100644 index 0000000..151ece5 --- /dev/null +++ b/services/udr/restapi/operations/status_management/get_status_urlbuilder.go @@ -0,0 +1,99 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" +) + +// GetStatusURL generates an URL for the get status operation +type GetStatusURL struct { + ID string + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) WithBasePath(bp string) *GetStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetStatusURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/udr/restapi/operations/status_management/show_status.go b/services/udr/restapi/operations/status_management/show_status.go new file mode 100644 index 0000000..7f29be7 --- /dev/null +++ b/services/udr/restapi/operations/status_management/show_status.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ShowStatusHandlerFunc turns a function with the right signature into a show status handler +type ShowStatusHandlerFunc func(ShowStatusParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ShowStatusHandlerFunc) Handle(params ShowStatusParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ShowStatusHandler interface for that can handle valid show status params +type ShowStatusHandler interface { + Handle(ShowStatusParams, interface{}) middleware.Responder +} + +// NewShowStatus creates a new http.Handler for the show status operation +func NewShowStatus(ctx *middleware.Context, handler ShowStatusHandler) *ShowStatus { + return &ShowStatus{Context: ctx, Handler: handler} +} + +/*ShowStatus swagger:route GET /status statusManagement showStatus + +Basic status of the system + +*/ +type ShowStatus struct { + Context *middleware.Context + Handler ShowStatusHandler +} + +func (o *ShowStatus) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewShowStatusParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/udr/restapi/operations/status_management/show_status_parameters.go b/services/udr/restapi/operations/status_management/show_status_parameters.go new file mode 100644 index 0000000..038bacc --- /dev/null +++ b/services/udr/restapi/operations/status_management/show_status_parameters.go @@ -0,0 +1,45 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" +) + +// NewShowStatusParams creates a new ShowStatusParams object +// no default values defined in spec. +func NewShowStatusParams() ShowStatusParams { + + return ShowStatusParams{} +} + +// ShowStatusParams contains all the bound params for the show status operation +// typically these are obtained from a http.Request +// +// swagger:parameters showStatus +type ShowStatusParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewShowStatusParams() beforehand. +func (o *ShowStatusParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/services/udr/restapi/operations/status_management/show_status_responses.go b/services/udr/restapi/operations/status_management/show_status_responses.go new file mode 100644 index 0000000..0320f6e --- /dev/null +++ b/services/udr/restapi/operations/status_management/show_status_responses.go @@ -0,0 +1,58 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// ShowStatusOKCode is the HTTP code returned for type ShowStatusOK +const ShowStatusOKCode int = 200 + +/*ShowStatusOK Status information of the system + +swagger:response showStatusOK +*/ +type ShowStatusOK struct { + + /* + In: Body + */ + Payload *models.Status `json:"body,omitempty"` +} + +// NewShowStatusOK creates ShowStatusOK with default headers values +func NewShowStatusOK() *ShowStatusOK { + + return &ShowStatusOK{} +} + +// WithPayload adds the payload to the show status o k response +func (o *ShowStatusOK) WithPayload(payload *models.Status) *ShowStatusOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the show status o k response +func (o *ShowStatusOK) SetPayload(payload *models.Status) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ShowStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/udr/restapi/operations/status_management/show_status_urlbuilder.go b/services/udr/restapi/operations/status_management/show_status_urlbuilder.go new file mode 100644 index 0000000..6efc165 --- /dev/null +++ b/services/udr/restapi/operations/status_management/show_status_urlbuilder.go @@ -0,0 +1,87 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package status_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" +) + +// ShowStatusURL generates an URL for the show status operation +type ShowStatusURL struct { + _basePath string +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) WithBasePath(bp string) *ShowStatusURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ShowStatusURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ShowStatusURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/status" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ShowStatusURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ShowStatusURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ShowStatusURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ShowStatusURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ShowStatusURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ShowStatusURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/udr/restapi/operations/trigger_management/exec_compactation.go b/services/udr/restapi/operations/trigger_management/exec_compactation.go new file mode 100644 index 0000000..bafc908 --- /dev/null +++ b/services/udr/restapi/operations/trigger_management/exec_compactation.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// ExecCompactationHandlerFunc turns a function with the right signature into a exec compactation handler +type ExecCompactationHandlerFunc func(ExecCompactationParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ExecCompactationHandlerFunc) Handle(params ExecCompactationParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ExecCompactationHandler interface for that can handle valid exec compactation params +type ExecCompactationHandler interface { + Handle(ExecCompactationParams, interface{}) middleware.Responder +} + +// NewExecCompactation creates a new http.Handler for the exec compactation operation +func NewExecCompactation(ctx *middleware.Context, handler ExecCompactationHandler) *ExecCompactation { + return &ExecCompactation{Context: ctx, Handler: handler} +} + +/*ExecCompactation swagger:route GET /trigger/compact triggerManagement execCompactation + +Compactation task trigger + +*/ +type ExecCompactation struct { + Context *middleware.Context + Handler ExecCompactationHandler +} + +func (o *ExecCompactation) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewExecCompactationParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/udr/restapi/operations/trigger_management/exec_compactation_parameters.go b/services/udr/restapi/operations/trigger_management/exec_compactation_parameters.go new file mode 100644 index 0000000..482735e --- /dev/null +++ b/services/udr/restapi/operations/trigger_management/exec_compactation_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// NewExecCompactationParams creates a new ExecCompactationParams object +// no default values defined in spec. +func NewExecCompactationParams() ExecCompactationParams { + + return ExecCompactationParams{} +} + +// ExecCompactationParams contains all the bound params for the exec compactation operation +// typically these are obtained from a http.Request +// +// swagger:parameters execCompactation +type ExecCompactationParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Switch for using 15m boundaries instead of 8h + In: query + */ + FastMode *bool + /*Datetime from which to get the usage report + In: query + */ + From *strfmt.DateTime + /*Datetime until which to get the usage report + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewExecCompactationParams() beforehand. +func (o *ExecCompactationParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFastMode, qhkFastMode, _ := qs.GetOK("fast_mode") + if err := o.bindFastMode(qFastMode, qhkFastMode, route.Formats); err != nil { + res = append(res, err) + } + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFastMode binds and validates parameter FastMode from query. +func (o *ExecCompactationParams) bindFastMode(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + value, err := swag.ConvertBool(raw) + if err != nil { + return errors.InvalidType("fast_mode", "query", "bool", raw) + } + o.FastMode = &value + + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *ExecCompactationParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *ExecCompactationParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *ExecCompactationParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *ExecCompactationParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/udr/restapi/operations/trigger_management/exec_compactation_responses.go b/services/udr/restapi/operations/trigger_management/exec_compactation_responses.go new file mode 100644 index 0000000..79b29a3 --- /dev/null +++ b/services/udr/restapi/operations/trigger_management/exec_compactation_responses.go @@ -0,0 +1,82 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// ExecCompactationOKCode is the HTTP code returned for type ExecCompactationOK +const ExecCompactationOKCode int = 200 + +/*ExecCompactationOK Compactation task executed successfully. + +swagger:response execCompactationOK +*/ +type ExecCompactationOK struct { +} + +// NewExecCompactationOK creates ExecCompactationOK with default headers values +func NewExecCompactationOK() *ExecCompactationOK { + + return &ExecCompactationOK{} +} + +// WriteResponse to the client +func (o *ExecCompactationOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(200) +} + +// ExecCompactationInternalServerErrorCode is the HTTP code returned for type ExecCompactationInternalServerError +const ExecCompactationInternalServerErrorCode int = 500 + +/*ExecCompactationInternalServerError Something unexpected happend, error raised + +swagger:response execCompactationInternalServerError +*/ +type ExecCompactationInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewExecCompactationInternalServerError creates ExecCompactationInternalServerError with default headers values +func NewExecCompactationInternalServerError() *ExecCompactationInternalServerError { + + return &ExecCompactationInternalServerError{} +} + +// WithPayload adds the payload to the exec compactation internal server error response +func (o *ExecCompactationInternalServerError) WithPayload(payload *models.ErrorResponse) *ExecCompactationInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the exec compactation internal server error response +func (o *ExecCompactationInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ExecCompactationInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/udr/restapi/operations/trigger_management/exec_compactation_urlbuilder.go b/services/udr/restapi/operations/trigger_management/exec_compactation_urlbuilder.go new file mode 100644 index 0000000..698a5c7 --- /dev/null +++ b/services/udr/restapi/operations/trigger_management/exec_compactation_urlbuilder.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package trigger_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// ExecCompactationURL generates an URL for the exec compactation operation +type ExecCompactationURL struct { + FastMode *bool + From *strfmt.DateTime + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecCompactationURL) WithBasePath(bp string) *ExecCompactationURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *ExecCompactationURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ExecCompactationURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/trigger/compact" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fastModeQ string + if o.FastMode != nil { + fastModeQ = swag.FormatBool(*o.FastMode) + } + if fastModeQ != "" { + qs.Set("fast_mode", fastModeQ) + } + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *ExecCompactationURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *ExecCompactationURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ExecCompactationURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ExecCompactationURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ExecCompactationURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *ExecCompactationURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/udr/restapi/operations/u_d_r_management_api_api.go b/services/udr/restapi/operations/u_d_r_management_api_api.go new file mode 100644 index 0000000..cf5a711 --- /dev/null +++ b/services/udr/restapi/operations/u_d_r_management_api_api.go @@ -0,0 +1,418 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "net/http" + "strings" + + "github.com/go-openapi/errors" + "github.com/go-openapi/loads" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/runtime/security" + "github.com/go-openapi/spec" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/metrics_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/usage_management" +) + +// NewUDRManagementAPIAPI creates a new UDRManagementAPI instance +func NewUDRManagementAPIAPI(spec *loads.Document) *UDRManagementAPIAPI { + return &UDRManagementAPIAPI{ + handlers: make(map[string]map[string]http.Handler), + formats: strfmt.Default, + defaultConsumes: "application/json", + defaultProduces: "application/json", + customConsumers: make(map[string]runtime.Consumer), + customProducers: make(map[string]runtime.Producer), + PreServerShutdown: func() {}, + ServerShutdown: func() {}, + spec: spec, + useSwaggerUI: false, + ServeError: errors.ServeError, + BasicAuthenticator: security.BasicAuth, + APIKeyAuthenticator: security.APIKeyAuth, + BearerAuthenticator: security.BearerAuth, + + JSONConsumer: runtime.JSONConsumer(), + + JSONProducer: runtime.JSONProducer(), + + TriggerManagementExecCompactationHandler: trigger_management.ExecCompactationHandlerFunc(func(params trigger_management.ExecCompactationParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation trigger_management.ExecCompactation has not yet been implemented") + }), + MetricsManagementGetMetricsHandler: metrics_management.GetMetricsHandlerFunc(func(params metrics_management.GetMetricsParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation metrics_management.GetMetrics has not yet been implemented") + }), + StatusManagementGetStatusHandler: status_management.GetStatusHandlerFunc(func(params status_management.GetStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.GetStatus has not yet been implemented") + }), + UsageManagementGetSystemUsageHandler: usage_management.GetSystemUsageHandlerFunc(func(params usage_management.GetSystemUsageParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation usage_management.GetSystemUsage has not yet been implemented") + }), + UsageManagementGetUsageHandler: usage_management.GetUsageHandlerFunc(func(params usage_management.GetUsageParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation usage_management.GetUsage has not yet been implemented") + }), + StatusManagementShowStatusHandler: status_management.ShowStatusHandlerFunc(func(params status_management.ShowStatusParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation status_management.ShowStatus has not yet been implemented") + }), + + // Applies when the "X-API-KEY" header is set + APIKeyHeaderAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyHeader) X-API-KEY from header param [X-API-KEY] has not yet been implemented") + }, + // Applies when the "api_key" query is set + APIKeyParamAuth: func(token string) (interface{}, error) { + return nil, errors.NotImplemented("api key auth (APIKeyParam) api_key from query param [api_key] has not yet been implemented") + }, + KeycloakAuth: func(token string, scopes []string) (interface{}, error) { + return nil, errors.NotImplemented("oauth2 bearer auth (Keycloak) has not yet been implemented") + }, + // default authorizer is authorized meaning no requests are blocked + APIAuthorizer: security.Authorized(), + } +} + +/*UDRManagementAPIAPI An API which supports creation, deletion, listing etc of UDR */ +type UDRManagementAPIAPI struct { + spec *loads.Document + context *middleware.Context + handlers map[string]map[string]http.Handler + formats strfmt.Registry + customConsumers map[string]runtime.Consumer + customProducers map[string]runtime.Producer + defaultConsumes string + defaultProduces string + Middleware func(middleware.Builder) http.Handler + useSwaggerUI bool + + // BasicAuthenticator generates a runtime.Authenticator from the supplied basic auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator + // APIKeyAuthenticator generates a runtime.Authenticator from the supplied token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator + // BearerAuthenticator generates a runtime.Authenticator from the supplied bearer token auth function. + // It has a default implementation in the security package, however you can replace it for your particular usage. + BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator + + // JSONConsumer registers a consumer for the following mime types: + // - application/json + JSONConsumer runtime.Consumer + + // JSONProducer registers a producer for the following mime types: + // - application/json + JSONProducer runtime.Producer + + // APIKeyHeaderAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key X-API-KEY provided in the header + APIKeyHeaderAuth func(string) (interface{}, error) + + // APIKeyParamAuth registers a function that takes a token and returns a principal + // it performs authentication based on an api key api_key provided in the query + APIKeyParamAuth func(string) (interface{}, error) + + // KeycloakAuth registers a function that takes an access token and a collection of required scopes and returns a principal + // it performs authentication based on an oauth2 bearer token provided in the request + KeycloakAuth func(string, []string) (interface{}, error) + + // APIAuthorizer provides access control (ACL/RBAC/ABAC) by providing access to the request and authenticated principal + APIAuthorizer runtime.Authorizer + + // TriggerManagementExecCompactationHandler sets the operation handler for the exec compactation operation + TriggerManagementExecCompactationHandler trigger_management.ExecCompactationHandler + // MetricsManagementGetMetricsHandler sets the operation handler for the get metrics operation + MetricsManagementGetMetricsHandler metrics_management.GetMetricsHandler + // StatusManagementGetStatusHandler sets the operation handler for the get status operation + StatusManagementGetStatusHandler status_management.GetStatusHandler + // UsageManagementGetSystemUsageHandler sets the operation handler for the get system usage operation + UsageManagementGetSystemUsageHandler usage_management.GetSystemUsageHandler + // UsageManagementGetUsageHandler sets the operation handler for the get usage operation + UsageManagementGetUsageHandler usage_management.GetUsageHandler + // StatusManagementShowStatusHandler sets the operation handler for the show status operation + StatusManagementShowStatusHandler status_management.ShowStatusHandler + // ServeError is called when an error is received, there is a default handler + // but you can set your own with this + ServeError func(http.ResponseWriter, *http.Request, error) + + // PreServerShutdown is called before the HTTP(S) server is shutdown + // This allows for custom functions to get executed before the HTTP(S) server stops accepting traffic + PreServerShutdown func() + + // ServerShutdown is called when the HTTP(S) server is shut down and done + // handling all active connections and does not accept connections any more + ServerShutdown func() + + // Custom command line argument groups with their descriptions + CommandLineOptionsGroups []swag.CommandLineOptionsGroup + + // User defined logger function. + Logger func(string, ...interface{}) +} + +// UseRedoc for documentation at /docs +func (o *UDRManagementAPIAPI) UseRedoc() { + o.useSwaggerUI = false +} + +// UseSwaggerUI for documentation at /docs +func (o *UDRManagementAPIAPI) UseSwaggerUI() { + o.useSwaggerUI = true +} + +// SetDefaultProduces sets the default produces media type +func (o *UDRManagementAPIAPI) SetDefaultProduces(mediaType string) { + o.defaultProduces = mediaType +} + +// SetDefaultConsumes returns the default consumes media type +func (o *UDRManagementAPIAPI) SetDefaultConsumes(mediaType string) { + o.defaultConsumes = mediaType +} + +// SetSpec sets a spec that will be served for the clients. +func (o *UDRManagementAPIAPI) SetSpec(spec *loads.Document) { + o.spec = spec +} + +// DefaultProduces returns the default produces media type +func (o *UDRManagementAPIAPI) DefaultProduces() string { + return o.defaultProduces +} + +// DefaultConsumes returns the default consumes media type +func (o *UDRManagementAPIAPI) DefaultConsumes() string { + return o.defaultConsumes +} + +// Formats returns the registered string formats +func (o *UDRManagementAPIAPI) Formats() strfmt.Registry { + return o.formats +} + +// RegisterFormat registers a custom format validator +func (o *UDRManagementAPIAPI) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { + o.formats.Add(name, format, validator) +} + +// Validate validates the registrations in the UDRManagementAPIAPI +func (o *UDRManagementAPIAPI) Validate() error { + var unregistered []string + + if o.JSONConsumer == nil { + unregistered = append(unregistered, "JSONConsumer") + } + + if o.JSONProducer == nil { + unregistered = append(unregistered, "JSONProducer") + } + + if o.APIKeyHeaderAuth == nil { + unregistered = append(unregistered, "XAPIKEYAuth") + } + if o.APIKeyParamAuth == nil { + unregistered = append(unregistered, "APIKeyAuth") + } + if o.KeycloakAuth == nil { + unregistered = append(unregistered, "KeycloakAuth") + } + + if o.TriggerManagementExecCompactationHandler == nil { + unregistered = append(unregistered, "trigger_management.ExecCompactationHandler") + } + if o.MetricsManagementGetMetricsHandler == nil { + unregistered = append(unregistered, "metrics_management.GetMetricsHandler") + } + if o.StatusManagementGetStatusHandler == nil { + unregistered = append(unregistered, "status_management.GetStatusHandler") + } + if o.UsageManagementGetSystemUsageHandler == nil { + unregistered = append(unregistered, "usage_management.GetSystemUsageHandler") + } + if o.UsageManagementGetUsageHandler == nil { + unregistered = append(unregistered, "usage_management.GetUsageHandler") + } + if o.StatusManagementShowStatusHandler == nil { + unregistered = append(unregistered, "status_management.ShowStatusHandler") + } + + if len(unregistered) > 0 { + return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) + } + + return nil +} + +// ServeErrorFor gets a error handler for a given operation id +func (o *UDRManagementAPIAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { + return o.ServeError +} + +// AuthenticatorsFor gets the authenticators for the specified security schemes +func (o *UDRManagementAPIAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { + result := make(map[string]runtime.Authenticator) + for name := range schemes { + switch name { + case "APIKeyHeader": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyHeaderAuth) + + case "APIKeyParam": + scheme := schemes[name] + result[name] = o.APIKeyAuthenticator(scheme.Name, scheme.In, o.APIKeyParamAuth) + + case "Keycloak": + result[name] = o.BearerAuthenticator(name, o.KeycloakAuth) + + } + } + return result +} + +// Authorizer returns the registered authorizer +func (o *UDRManagementAPIAPI) Authorizer() runtime.Authorizer { + return o.APIAuthorizer +} + +// ConsumersFor gets the consumers for the specified media types. +// MIME type parameters are ignored here. +func (o *UDRManagementAPIAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { + result := make(map[string]runtime.Consumer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONConsumer + } + + if c, ok := o.customConsumers[mt]; ok { + result[mt] = c + } + } + return result +} + +// ProducersFor gets the producers for the specified media types. +// MIME type parameters are ignored here. +func (o *UDRManagementAPIAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { + result := make(map[string]runtime.Producer, len(mediaTypes)) + for _, mt := range mediaTypes { + switch mt { + case "application/json": + result["application/json"] = o.JSONProducer + } + + if p, ok := o.customProducers[mt]; ok { + result[mt] = p + } + } + return result +} + +// HandlerFor gets a http.Handler for the provided operation method and path +func (o *UDRManagementAPIAPI) HandlerFor(method, path string) (http.Handler, bool) { + if o.handlers == nil { + return nil, false + } + um := strings.ToUpper(method) + if _, ok := o.handlers[um]; !ok { + return nil, false + } + if path == "/" { + path = "" + } + h, ok := o.handlers[um][path] + return h, ok +} + +// Context returns the middleware context for the u d r management API API +func (o *UDRManagementAPIAPI) Context() *middleware.Context { + if o.context == nil { + o.context = middleware.NewRoutableContext(o.spec, o, nil) + } + + return o.context +} + +func (o *UDRManagementAPIAPI) initHandlerCache() { + o.Context() // don't care about the result, just that the initialization happened + if o.handlers == nil { + o.handlers = make(map[string]map[string]http.Handler) + } + + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/trigger/compact"] = trigger_management.NewExecCompactation(o.context, o.TriggerManagementExecCompactationHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/metrics"] = metrics_management.NewGetMetrics(o.context, o.MetricsManagementGetMetricsHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status/{id}"] = status_management.NewGetStatus(o.context, o.StatusManagementGetStatusHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/usage"] = usage_management.NewGetSystemUsage(o.context, o.UsageManagementGetSystemUsageHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/usage/{id}"] = usage_management.NewGetUsage(o.context, o.UsageManagementGetUsageHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/status"] = status_management.NewShowStatus(o.context, o.StatusManagementShowStatusHandler) +} + +// Serve creates a http handler to serve the API over HTTP +// can be used directly in http.ListenAndServe(":8000", api.Serve(nil)) +func (o *UDRManagementAPIAPI) Serve(builder middleware.Builder) http.Handler { + o.Init() + + if o.Middleware != nil { + return o.Middleware(builder) + } + if o.useSwaggerUI { + return o.context.APIHandlerSwaggerUI(builder) + } + return o.context.APIHandler(builder) +} + +// Init allows you to just initialize the handler cache, you can then recompose the middleware as you see fit +func (o *UDRManagementAPIAPI) Init() { + if len(o.handlers) == 0 { + o.initHandlerCache() + } +} + +// RegisterConsumer allows you to add (or override) a consumer for a media type. +func (o *UDRManagementAPIAPI) RegisterConsumer(mediaType string, consumer runtime.Consumer) { + o.customConsumers[mediaType] = consumer +} + +// RegisterProducer allows you to add (or override) a producer for a media type. +func (o *UDRManagementAPIAPI) RegisterProducer(mediaType string, producer runtime.Producer) { + o.customProducers[mediaType] = producer +} + +// AddMiddlewareFor adds a http middleware to existing handler +func (o *UDRManagementAPIAPI) AddMiddlewareFor(method, path string, builder middleware.Builder) { + um := strings.ToUpper(method) + if path == "/" { + path = "" + } + o.Init() + if h, ok := o.handlers[um][path]; ok { + o.handlers[method][path] = builder(h) + } +} diff --git a/services/udr/restapi/operations/usage_management/get_system_usage.go b/services/udr/restapi/operations/usage_management/get_system_usage.go new file mode 100644 index 0000000..fed7a73 --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_system_usage.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetSystemUsageHandlerFunc turns a function with the right signature into a get system usage handler +type GetSystemUsageHandlerFunc func(GetSystemUsageParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetSystemUsageHandlerFunc) Handle(params GetSystemUsageParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetSystemUsageHandler interface for that can handle valid get system usage params +type GetSystemUsageHandler interface { + Handle(GetSystemUsageParams, interface{}) middleware.Responder +} + +// NewGetSystemUsage creates a new http.Handler for the get system usage operation +func NewGetSystemUsage(ctx *middleware.Context, handler GetSystemUsageHandler) *GetSystemUsage { + return &GetSystemUsage{Context: ctx, Handler: handler} +} + +/*GetSystemUsage swagger:route GET /usage usageManagement getSystemUsage + +Detailed report covering all accounts within the specified time window + +*/ +type GetSystemUsage struct { + Context *middleware.Context + Handler GetSystemUsageHandler +} + +func (o *GetSystemUsage) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetSystemUsageParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/udr/restapi/operations/usage_management/get_system_usage_parameters.go b/services/udr/restapi/operations/usage_management/get_system_usage_parameters.go new file mode 100644 index 0000000..b649605 --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_system_usage_parameters.go @@ -0,0 +1,195 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetSystemUsageParams creates a new GetSystemUsageParams object +// no default values defined in spec. +func NewGetSystemUsageParams() GetSystemUsageParams { + + return GetSystemUsageParams{} +} + +// GetSystemUsageParams contains all the bound params for the get system usage operation +// typically these are obtained from a http.Request +// +// swagger:parameters getSystemUsage +type GetSystemUsageParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to get the usage report + In: query + */ + From *strfmt.DateTime + /*List of ids to be queried + In: query + */ + Idlist *string + /*Metric(s) to get the usage report + In: query + */ + Metric *string + /*Datetime until which to get the usage report + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetSystemUsageParams() beforehand. +func (o *GetSystemUsageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + qIdlist, qhkIdlist, _ := qs.GetOK("idlist") + if err := o.bindIdlist(qIdlist, qhkIdlist, route.Formats); err != nil { + res = append(res, err) + } + + qMetric, qhkMetric, _ := qs.GetOK("metric") + if err := o.bindMetric(qMetric, qhkMetric, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetSystemUsageParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *GetSystemUsageParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindIdlist binds and validates parameter Idlist from query. +func (o *GetSystemUsageParams) bindIdlist(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Idlist = &raw + + return nil +} + +// bindMetric binds and validates parameter Metric from query. +func (o *GetSystemUsageParams) bindMetric(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Metric = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetSystemUsageParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *GetSystemUsageParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/udr/restapi/operations/usage_management/get_system_usage_responses.go b/services/udr/restapi/operations/usage_management/get_system_usage_responses.go new file mode 100644 index 0000000..34d520b --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_system_usage_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetSystemUsageOKCode is the HTTP code returned for type GetSystemUsageOK +const GetSystemUsageOKCode int = 200 + +/*GetSystemUsageOK Description of a successfully operation + +swagger:response getSystemUsageOK +*/ +type GetSystemUsageOK struct { + + /* + In: Body + */ + Payload []*models.UReport `json:"body,omitempty"` +} + +// NewGetSystemUsageOK creates GetSystemUsageOK with default headers values +func NewGetSystemUsageOK() *GetSystemUsageOK { + + return &GetSystemUsageOK{} +} + +// WithPayload adds the payload to the get system usage o k response +func (o *GetSystemUsageOK) WithPayload(payload []*models.UReport) *GetSystemUsageOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get system usage o k response +func (o *GetSystemUsageOK) SetPayload(payload []*models.UReport) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSystemUsageOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.UReport, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetSystemUsageInternalServerErrorCode is the HTTP code returned for type GetSystemUsageInternalServerError +const GetSystemUsageInternalServerErrorCode int = 500 + +/*GetSystemUsageInternalServerError Something unexpected happend, error raised + +swagger:response getSystemUsageInternalServerError +*/ +type GetSystemUsageInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetSystemUsageInternalServerError creates GetSystemUsageInternalServerError with default headers values +func NewGetSystemUsageInternalServerError() *GetSystemUsageInternalServerError { + + return &GetSystemUsageInternalServerError{} +} + +// WithPayload adds the payload to the get system usage internal server error response +func (o *GetSystemUsageInternalServerError) WithPayload(payload *models.ErrorResponse) *GetSystemUsageInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get system usage internal server error response +func (o *GetSystemUsageInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetSystemUsageInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/udr/restapi/operations/usage_management/get_system_usage_urlbuilder.go b/services/udr/restapi/operations/usage_management/get_system_usage_urlbuilder.go new file mode 100644 index 0000000..40a5857 --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_system_usage_urlbuilder.go @@ -0,0 +1,132 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + + "github.com/go-openapi/strfmt" +) + +// GetSystemUsageURL generates an URL for the get system usage operation +type GetSystemUsageURL struct { + From *strfmt.DateTime + Idlist *string + Metric *string + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSystemUsageURL) WithBasePath(bp string) *GetSystemUsageURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetSystemUsageURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetSystemUsageURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/usage" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var idlistQ string + if o.Idlist != nil { + idlistQ = *o.Idlist + } + if idlistQ != "" { + qs.Set("idlist", idlistQ) + } + + var metricQ string + if o.Metric != nil { + metricQ = *o.Metric + } + if metricQ != "" { + qs.Set("metric", metricQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetSystemUsageURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetSystemUsageURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetSystemUsageURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetSystemUsageURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetSystemUsageURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetSystemUsageURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/udr/restapi/operations/usage_management/get_usage.go b/services/udr/restapi/operations/usage_management/get_usage.go new file mode 100644 index 0000000..edc7ae4 --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_usage.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime/middleware" +) + +// GetUsageHandlerFunc turns a function with the right signature into a get usage handler +type GetUsageHandlerFunc func(GetUsageParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetUsageHandlerFunc) Handle(params GetUsageParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetUsageHandler interface for that can handle valid get usage params +type GetUsageHandler interface { + Handle(GetUsageParams, interface{}) middleware.Responder +} + +// NewGetUsage creates a new http.Handler for the get usage operation +func NewGetUsage(ctx *middleware.Context, handler GetUsageHandler) *GetUsage { + return &GetUsage{Context: ctx, Handler: handler} +} + +/*GetUsage swagger:route GET /usage/{id} usageManagement getUsage + +Detailed report covering of the account associated with the id within the specified time window + +*/ +type GetUsage struct { + Context *middleware.Context + Handler GetUsageHandler +} + +func (o *GetUsage) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + r = rCtx + } + var Params = NewGetUsageParams() + + uprinc, aCtx, err := o.Context.Authorize(r, route) + if err != nil { + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + if aCtx != nil { + r = aCtx + } + var principal interface{} + if uprinc != nil { + principal = uprinc + } + + if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params + o.Context.Respond(rw, r, route.Produces, route, err) + return + } + + res := o.Handler.Handle(Params, principal) // actually handle the request + + o.Context.Respond(rw, r, route.Produces, route, res) + +} diff --git a/services/udr/restapi/operations/usage_management/get_usage_parameters.go b/services/udr/restapi/operations/usage_management/get_usage_parameters.go new file mode 100644 index 0000000..8905a0d --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_usage_parameters.go @@ -0,0 +1,193 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/validate" +) + +// NewGetUsageParams creates a new GetUsageParams object +// no default values defined in spec. +func NewGetUsageParams() GetUsageParams { + + return GetUsageParams{} +} + +// GetUsageParams contains all the bound params for the get usage operation +// typically these are obtained from a http.Request +// +// swagger:parameters getUsage +type GetUsageParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Datetime from which to get the usage report + In: query + */ + From *strfmt.DateTime + /*Id of the account to be checked + Required: true + In: path + */ + ID string + /*Metric(s) to get the usage report + In: query + */ + Metric *string + /*Datetime until which to get the usage report + In: query + */ + To *strfmt.DateTime +} + +// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface +// for simple values it will use straight method calls. +// +// To ensure default values, the struct must have been initialized with NewGetUsageParams() beforehand. +func (o *GetUsageParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { + var res []error + + o.HTTPRequest = r + + qs := runtime.Values(r.URL.Query()) + + qFrom, qhkFrom, _ := qs.GetOK("from") + if err := o.bindFrom(qFrom, qhkFrom, route.Formats); err != nil { + res = append(res, err) + } + + rID, rhkID, _ := route.Params.GetOK("id") + if err := o.bindID(rID, rhkID, route.Formats); err != nil { + res = append(res, err) + } + + qMetric, qhkMetric, _ := qs.GetOK("metric") + if err := o.bindMetric(qMetric, qhkMetric, route.Formats); err != nil { + res = append(res, err) + } + + qTo, qhkTo, _ := qs.GetOK("to") + if err := o.bindTo(qTo, qhkTo, route.Formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindFrom binds and validates parameter From from query. +func (o *GetUsageParams) bindFrom(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("from", "query", "strfmt.DateTime", raw) + } + o.From = (value.(*strfmt.DateTime)) + + if err := o.validateFrom(formats); err != nil { + return err + } + + return nil +} + +// validateFrom carries on validations for parameter From +func (o *GetUsageParams) validateFrom(formats strfmt.Registry) error { + + if err := validate.FormatOf("from", "query", "datetime", o.From.String(), formats); err != nil { + return err + } + return nil +} + +// bindID binds and validates parameter ID from path. +func (o *GetUsageParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: true + // Parameter is provided by construction from the route + + o.ID = raw + + return nil +} + +// bindMetric binds and validates parameter Metric from query. +func (o *GetUsageParams) bindMetric(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + o.Metric = &raw + + return nil +} + +// bindTo binds and validates parameter To from query. +func (o *GetUsageParams) bindTo(rawData []string, hasKey bool, formats strfmt.Registry) error { + var raw string + if len(rawData) > 0 { + raw = rawData[len(rawData)-1] + } + + // Required: false + // AllowEmptyValue: false + if raw == "" { // empty values pass all other validations + return nil + } + + // Format: datetime + value, err := formats.Parse("datetime", raw) + if err != nil { + return errors.InvalidType("to", "query", "strfmt.DateTime", raw) + } + o.To = (value.(*strfmt.DateTime)) + + if err := o.validateTo(formats); err != nil { + return err + } + + return nil +} + +// validateTo carries on validations for parameter To +func (o *GetUsageParams) validateTo(formats strfmt.Registry) error { + + if err := validate.FormatOf("to", "query", "datetime", o.To.String(), formats); err != nil { + return err + } + return nil +} diff --git a/services/udr/restapi/operations/usage_management/get_usage_responses.go b/services/udr/restapi/operations/usage_management/get_usage_responses.go new file mode 100644 index 0000000..8d5ca1b --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_usage_responses.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "net/http" + + "github.com/go-openapi/runtime" + + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" +) + +// GetUsageOKCode is the HTTP code returned for type GetUsageOK +const GetUsageOKCode int = 200 + +/*GetUsageOK Description of a successfully operation + +swagger:response getUsageOK +*/ +type GetUsageOK struct { + + /* + In: Body + */ + Payload []*models.UReport `json:"body,omitempty"` +} + +// NewGetUsageOK creates GetUsageOK with default headers values +func NewGetUsageOK() *GetUsageOK { + + return &GetUsageOK{} +} + +// WithPayload adds the payload to the get usage o k response +func (o *GetUsageOK) WithPayload(payload []*models.UReport) *GetUsageOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage o k response +func (o *GetUsageOK) SetPayload(payload []*models.UReport) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(200) + payload := o.Payload + if payload == nil { + // return empty array + payload = make([]*models.UReport, 0, 50) + } + + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } +} + +// GetUsageInternalServerErrorCode is the HTTP code returned for type GetUsageInternalServerError +const GetUsageInternalServerErrorCode int = 500 + +/*GetUsageInternalServerError Something unexpected happend, error raised + +swagger:response getUsageInternalServerError +*/ +type GetUsageInternalServerError struct { + + /* + In: Body + */ + Payload *models.ErrorResponse `json:"body,omitempty"` +} + +// NewGetUsageInternalServerError creates GetUsageInternalServerError with default headers values +func NewGetUsageInternalServerError() *GetUsageInternalServerError { + + return &GetUsageInternalServerError{} +} + +// WithPayload adds the payload to the get usage internal server error response +func (o *GetUsageInternalServerError) WithPayload(payload *models.ErrorResponse) *GetUsageInternalServerError { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get usage internal server error response +func (o *GetUsageInternalServerError) SetPayload(payload *models.ErrorResponse) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetUsageInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.WriteHeader(500) + if o.Payload != nil { + payload := o.Payload + if err := producer.Produce(rw, payload); err != nil { + panic(err) // let the recovery middleware deal with this + } + } +} diff --git a/services/udr/restapi/operations/usage_management/get_usage_urlbuilder.go b/services/udr/restapi/operations/usage_management/get_usage_urlbuilder.go new file mode 100644 index 0000000..7ca9a83 --- /dev/null +++ b/services/udr/restapi/operations/usage_management/get_usage_urlbuilder.go @@ -0,0 +1,133 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package usage_management + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "errors" + "net/url" + golangswaggerpaths "path" + "strings" + + "github.com/go-openapi/strfmt" +) + +// GetUsageURL generates an URL for the get usage operation +type GetUsageURL struct { + ID string + + From *strfmt.DateTime + Metric *string + To *strfmt.DateTime + + _basePath string + // avoid unkeyed usage + _ struct{} +} + +// WithBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageURL) WithBasePath(bp string) *GetUsageURL { + o.SetBasePath(bp) + return o +} + +// SetBasePath sets the base path for this url builder, only required when it's different from the +// base path specified in the swagger spec. +// When the value of the base path is an empty string +func (o *GetUsageURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetUsageURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/usage/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetUsageURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/api/v1.0" + } + _result.Path = golangswaggerpaths.Join(_basePath, _path) + + qs := make(url.Values) + + var fromQ string + if o.From != nil { + fromQ = o.From.String() + } + if fromQ != "" { + qs.Set("from", fromQ) + } + + var metricQ string + if o.Metric != nil { + metricQ = *o.Metric + } + if metricQ != "" { + qs.Set("metric", metricQ) + } + + var toQ string + if o.To != nil { + toQ = o.To.String() + } + if toQ != "" { + qs.Set("to", toQ) + } + + _result.RawQuery = qs.Encode() + + return &_result, nil +} + +// Must is a helper function to panic when the url builder returns an error +func (o *GetUsageURL) Must(u *url.URL, err error) *url.URL { + if err != nil { + panic(err) + } + if u == nil { + panic("url can't be nil") + } + return u +} + +// String returns the string representation of the path with query string +func (o *GetUsageURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetUsageURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetUsageURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetUsageURL") + } + + base, err := o.Build() + if err != nil { + return nil, err + } + + base.Scheme = scheme + base.Host = host + return base, nil +} + +// StringFull returns the string representation of a complete url +func (o *GetUsageURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/services/udr/restapi/server.go b/services/udr/restapi/server.go new file mode 100644 index 0000000..77b66a0 --- /dev/null +++ b/services/udr/restapi/server.go @@ -0,0 +1,5 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package restapi + +// this file is intentionally empty. Otherwise go-swagger will generate a server which we don't want diff --git a/services/udr/run/cert.crt b/services/udr/run/cert.crt new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/udr/run/cert.crt @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/udr/run/config.toml b/services/udr/run/config.toml new file mode 100644 index 0000000..1bd9381 --- /dev/null +++ b/services/udr/run/config.toml @@ -0,0 +1,89 @@ +# Welcome to the configuration file for this +# +# ██████╗██╗ ██╗ ██████╗██╗ ██████╗ ██████╗ ███████╗ +# ██╔════╝╚██╗ ██╔╝██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝ +# ██║ ╚████╔╝ ██║ ██║ ██║ ██║██████╔╝███████╗ +# ██║ ╚██╔╝ ██║ ██║ ██║ ██║██╔═══╝ ╚════██║ +# ╚██████╗ ██║ ╚██████╗███████╗╚██████╔╝██║ ███████║ +# ╚═════╝ ╚═╝ ╚═════╝╚══════╝ ╚═════╝ ╚═╝ ╚══════╝ +# +# ██╗ █████╗ ██████╗ ███████╗ +# ██║ ██╔══██╗██╔══██╗██╔════╝ +# ██║ ███████║██████╔╝███████╗ +# ██║ ██╔══██║██╔══██╗╚════██║ +# ███████╗██║ ██║██████╔╝███████║ +# ╚══════╝╚═╝ ╚═╝╚═════╝ ╚══════╝ +# +# uService! + +[APIKEY] +Enabled = true +Key = "X-API-KEY" +Place = "header" +Token = "1234567890abcdefghi" + +[DATABASE] +# Duration style: Xh, Xm, Xs... +CacheRetention = "23h" +DBName = "cyclops" +Host = "localhost" +Password = "pass1234" +Port = 5432 +# SSLMode = enable | disable +SSLMode = "disable" +UserName = "cyclops" + +[EVENTS] +Filters = [ "filter1", "filter2" ] + +[GENERAL] +CertificateFile = "./cert.crt" +CertificateKey = "./key.key" +CORSEnabled = false +CORSHeaders = [ "*" ] +CORSMethods = [ "GET", "POST" ] +CORSOrigins = [ "" ] +HttpsEnabled = false +InsecureSkipVerify = false +# "" for no file-logging +LogFile = "" +# LogLevel = TRACE | DEBUG | INFO | WARNING | ERROR +LogLevel = "TRACE" +LogToConsole = true +ServerPort = 8000 + +[GENERAL.SERVICES] +Billing = "billing:8000" +CDR = "cdr:8000" +CreditManager = "creditsystem:8000" +CustomerDB = "customerdb:8000" +EventsEngine = "eventsengine:8000" +PlanManager = "planmanager:8000" +UDR = "udr:8000" + +[KAFKA] +Brokers = [ "kafka1:9092", "kafka2:9092", "kafka3:9092" ] +CDRIn = [ "CDR" ] +CDROut = [ "Credit" ] +Credit-SystemIn = [ "Credit" ] +EventsEngineIn = [ "Events" ] +# -1 for the most recent +# -2 for the first in the partition +# Anyother for a specific offset +Offset = "-1" +Partition = "0" +SizeMin = 10e3 +SizeMax = 10e6 +UDRIn = [ "UDR" ] +UDROut = [ "CDR" ] + +[PLANS] +Default = "-1" +Education = "-2" + +[PROMETHEUS] +Host = "prometheus:9090" +MetricsExport = true +MetricsPort = "9000" +MetricsRoute = "/metrics" + diff --git a/services/udr/run/docker-compose.yml b/services/udr/run/docker-compose.yml new file mode 100644 index 0000000..8a6e52e --- /dev/null +++ b/services/udr/run/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3' + +services: + + db: + image: postgres:latest + networks: + - cyclopsnet + environment: + POSTGRES_PASSWORD: pass1234 + POSTGRES_DB: cyclops + POSTGRES_USER: cyclops + ports: + - 5432:5432 + volumes: + - postgresql:/var/lib/postgresql + # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52 + - postgresql_data:/var/lib/postgresql/data + + + service: + image: SERVICE:latest + restart: always + environment: + WAIT_HOSTS: db:5432 + networks: + - cyclopsnet + depends_on: + - "db" + ports: + - 8000:8000 + volumes: + - ${PWD}/config.toml:/config.toml + - ${PWD}/cert.crt:/cert.crt + - ${PWD}/key.key:/key.key + +networks: + cyclopsnet: + driver: bridge + +volumes: + postgresql: + postgresql_data: diff --git a/services/udr/run/key.key b/services/udr/run/key.key new file mode 100644 index 0000000..d372b10 --- /dev/null +++ b/services/udr/run/key.key @@ -0,0 +1 @@ +DUMMY FILE! diff --git a/services/udr/server/cache.go b/services/udr/server/cache.go new file mode 100644 index 0000000..a1407ac --- /dev/null +++ b/services/udr/server/cache.go @@ -0,0 +1,553 @@ +package main + +import ( + "context" + "net/url" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + cdrClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client" + cdrUsage "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/cdr/client/usage_management" + cusClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client" + cusCustomer "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/customer_management" + cusProduct "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/product_management" + cusReseller "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/customerdb/client/reseller_management" + pmClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client" + pmBundle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/bundle_management" + pmCycle "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/cycle_management" + pmPlan "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/plan_management" + pmSku "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/plan-manager/client/sku_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/cacheManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheStart handles the initialization of the cache mechanism service. +// Returns: +// - A cacheManager reference struct already initialized and ready to be used. +func cacheStart(metrics *prometheus.GaugeVec) *cacheManager.CacheManager { + + l.Trace.Printf("[CACHE][INIT] Intializing cache mechanism.\n") + + cacheDuration, _ := time.ParseDuration(cfg.DB.CacheRetention) + + c := cacheManager.New(metrics, cacheDuration, cfg.APIKey.Token) + + resellerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusReseller.NewGetResellerParams().WithID(i) + + r, e := client.ResellerManagement.GetReseller(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the reseller with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusReseller.NewListResellersParams() + + r, e := client.ResellerManagement.ListResellers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of resellers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + customerFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusCustomer.NewGetCustomerParams().WithID(i) + + r, e := client.CustomerManagement.GetCustomer(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the customer with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusCustomer.NewListCustomersParams() + + r, e := client.CustomerManagement.ListCustomers(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of customers. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + productFunction := func(id interface{}, token string) (interface{}, error) { + + config := cusClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["customerdb"], + Path: cusClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := cusClient.New(config) + ctx := context.Background() + + i := id.(string) + + if i != "ALL" { + + params := cusProduct.NewGetProductParams().WithID(i) + + r, e := client.ProductManagement.GetProduct(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the product with id [ %v ]. Error: %v", i, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := cusProduct.NewListProductsParams() + + r, e := client.ProductManagement.ListProducts(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CUSDB-FUNCTION] There was a problem while retrieving the list of products. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + // id == id0[,id1,...,idN]?from?to + cdrFunction := func(id interface{}, token string) (interface{}, error) { + + config := cdrClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["cdr"], + Path: cdrClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + idSplit := strings.SplitN(id.(string), "?", 3) + + i := idSplit[0] + + from, e := time.Parse(time.RFC3339Nano, idSplit[1]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[1], e) + + return nil, e + + } + + f := (strfmt.DateTime)(from) + + to, e := time.Parse(time.RFC3339Nano, idSplit[2]) + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while parsing the datetime [ %v ]. Error: %v", idSplit[2], e) + + return nil, e + + } + + t := (strfmt.DateTime)(to) + + client := cdrClient.New(config) + ctx := context.Background() + + if strings.Contains(i, ",") { + + params := cdrUsage.NewGetSystemUsageParams().WithIdlist(&i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + if i != "ALL" { + + params := cdrUsage.NewGetUsageParams().WithID(i).WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving the CDRs under the id [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := cdrUsage.NewGetSystemUsageParams().WithFrom(&f).WithTo(&t) + + r, e := client.UsageManagement.GetSystemUsage(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CDR-FUNCTION] There was a problem while retrieving all the CDRs from the system. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + skuFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmSku.NewGetSkuParams().WithID(id.(string)) + + r, e := client.SkuManagement.GetSku(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the sku [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return r.Payload, nil + + } + + params := pmSku.NewListSkusParams() + + r, e := client.SkuManagement.ListSkus(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][SKU-FUNCTION] There was a problem while retrieving the skus list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + planFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + var planID string + + if i, exists := cfg.DefaultPlans[strings.ToLower(id.(string))]; exists { + + planID = i + + } else { + + planID = id.(string) + + } + + params := pmPlan.NewGetCompletePlanParams().WithID(planID) + + r, e := client.PlanManagement.GetCompletePlan(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmPlan.NewListCompletePlansParams() + + r, e := client.PlanManagement.ListCompletePlans(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][PLAN-FUNCTION] There was a problem while retrieving the plan list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + bundleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + if id.(string) != "ALL" { + + params := pmBundle.NewGetSkuBundleParams().WithID(id.(string)) + + r, e := client.BundleManagement.GetSkuBundle(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle [ %v ]. Error: %v", id, e) + + return nil, e + + } + + return *r.Payload, nil + + } + + params := pmBundle.NewListSkuBundlesParams() + + r, e := client.BundleManagement.ListSkuBundles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][BUNDLE-FUNCTION] There was a problem while retrieving the skubundle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + cycleFunction := func(id interface{}, token string) (interface{}, error) { + + config := pmClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["planmanager"], + Path: pmClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + if token != "" { + + config.AuthInfo = httptransport.BearerToken(token) + + } + + client := pmClient.New(config) + ctx := context.Background() + + var params *pmCycle.ListCyclesParams + + if id.(string) == "ALL" { + + params = pmCycle.NewListCyclesParams() + + } else { + + ty := id.(string) + + params = pmCycle.NewListCyclesParams().WithType(&ty) + + } + + r, e := client.CycleManagement.ListCycles(ctx, params) + + if e != nil { + + l.Warning.Printf("[CACHE][CYCLE-FUNCTION] There was a problem while retrieving the cycle list. Error: %v", e) + + return nil, e + + } + + return r.Payload, nil + + } + + c.Add("reseller", resellerFunction) + l.Trace.Printf("[CACHE][INIT] Reseller fetcher added to the cache.\n") + + c.Add("customer", customerFunction) + l.Trace.Printf("[CACHE][INIT] Customer fetcher added to the cache.\n") + + c.Add("product", productFunction) + l.Trace.Printf("[CACHE][INIT] Product fetcher added to the cache.\n") + + c.Add("cdr", cdrFunction) + l.Trace.Printf("[CACHE][INIT] CDR usage fetcher added to the cache.\n") + + c.Add("sku", skuFunction) + l.Trace.Printf("[CACHE][INIT] SKU fetcher added to the cache.\n") + + c.Add("plan", planFunction) + l.Trace.Printf("[CACHE][INIT] Plan fetcher added to the cache.\n") + + c.Add("bundle", bundleFunction) + l.Trace.Printf("[CACHE][INIT] SkuBundle fetcher added to the cache.\n") + + c.Add("cycle", cycleFunction) + l.Trace.Printf("[CACHE][INIT] Life Cycle fetcher added to the cache.\n") + + return c + +} diff --git a/services/udr/server/cacheManager/cacheManager.go b/services/udr/server/cacheManager/cacheManager.go new file mode 100644 index 0000000..9da44a3 --- /dev/null +++ b/services/udr/server/cacheManager/cacheManager.go @@ -0,0 +1,277 @@ +package cacheManager + +import ( + "fmt" + "strings" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +// cacheFetchFunction it will need the id to retrieve and as and option a Bearer +// Keycloak token can be provided when called. +// It shall return the object and errors in case of problems. +type cacheFetchFunction func(interface{}, string) (interface{}, error) + +// cache struct is the main "object" which handles the cache and its items. +// It also contains a map with the conversions of interfaces to strings. +type cache struct { + ////conversionDictionary map[string]string + data map[string]*cacheItem + fetchers map[string]cacheFetchFunction + mutex sync.RWMutex +} + +// cacheItem struct referes to the data of each element saved in the cache. +type cacheItem struct { + fetcher cacheFetchFunction + lastUpdate time.Time + value interface{} +} + +// CacheManager is the struct defined to group and contain all the methods +// that interact with the caching mechanism. +type CacheManager struct { + APIKey string + duration time.Duration + metrics *prometheus.GaugeVec + store cache +} + +// New is the function to create the struct CacheManager. +// Parameters: +// - t: a time.Duration with the max duration alive of the cache elements. +// - k: string containing the APIKey/token in case of need. +// Returns: +// - CacheManager: struct to interact with CacheManager subsystem functionalities. +func New(metrics *prometheus.GaugeVec, t time.Duration, k string) *CacheManager { + + l.Trace.Printf("[CACHE] Initializing the cache service.\n") + + c := CacheManager{ + APIKey: k, + duration: t, + metrics: metrics, + store: cache{ + data: make(map[string]*cacheItem), + fetchers: make(map[string]cacheFetchFunction), + }, + } + + return &c + +} + +// Add function job is to insert a new model in the cache. +// What it does is link the model with a fetching function and, if wanted, with +// a plain text name, so later in order to retrieve things from the cache they +// can be refereced either by the struct model or the plain text name. +// Paramenters: +// - plainName: a case insensitive name/alias to retrieve the data. +// - fetcher: the cacheFetchFunction used to retrieve the data. +func (c *CacheManager) Add(plainName string, fetcher cacheFetchFunction) { + + l.Trace.Printf("[CACHE] Adding a new object fetcher in the cache.\n") + + key := strings.ToUpper(plainName) + + c.store.mutex.Lock() + + c.store.fetchers[key] = fetcher + + c.store.mutex.Unlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Models in Cache"}).Inc() + + return + +} + +// fetch function job is to retrieve a new and updated copy of the remote object. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) fetch(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + c.store.mutex.RLock() + + object := c.store.data[item] + + c.store.mutex.RUnlock() + + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := object.fetcher(id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + object.value = uValue + object.lastUpdate = time.Now() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// fetch function job is to create the new item in the cache and retrieve a new +// and updated initial copy of the remote object to be saved in the cache. +// Paramenters: +// - item: a string used as key-value in the cache storage to identify the item +// that is going to be updated. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - e: error in case of something went wrong while setting up the new association. +func (c *CacheManager) init(item string, token string) (e error) { + + l.Trace.Printf("[CACHE] Fetching the item [ %v ] from the remote location.\n", item) + + key := strings.Split(item, "-")[0] + id := strings.SplitN(item, "-", 2)[1] + + uValue, e := c.store.fetchers[key](id, token) + + if e == nil { + + l.Trace.Printf("[CACHE] Item [ %v ] retrieved from the remote location and saved in the cache.\n", item) + + i := cacheItem{ + fetcher: c.store.fetchers[key], + lastUpdate: time.Now(), + value: uValue, + } + + c.store.mutex.Lock() + + c.store.data[item] = &i + + c.store.mutex.Unlock() + + } else { + + l.Warning.Printf("[CACHE] Something went wrong while retrieving the item. Error: %v\n", e) + + } + + return + +} + +// key is a function to ensure that the creation of the the item key for the +// cache is consistent across all the functions. +// Paramenters: +// - id: the reference id of the object to be retrieved +// - model: the alias text used to identify the source of objects. +// Returns: +// - s: the key string +func (c *CacheManager) key(id interface{}, model string) (s string) { + + s = fmt.Sprintf("%v-%v", strings.ToUpper(model), id) + + return + +} + +// Get function job is to retrieve an object from the cache or fetch it from the +// source and upgrade the copy in the cache in case the expiration time has been +// exceeded. +// Paramenters: +// - id: the reference id of the object. +// - model: the text alias set to reference the model. +// - token: Keycloak Bearer token, completely optional. +// Returns: +// - The object associated with the request +// - An error raised in case something went wrong while retrieving the object. +func (c *CacheManager) Get(id interface{}, model string, token string) (interface{}, error) { + + l.Trace.Printf("[CACHE] Retrieving object [ %v, %v ] from the cache.\n", id, model) + + item := c.key(id, model) + + object, exists := c.store.data[item] + + if !exists { + + l.Trace.Printf("[CACHE] Object [ %v ] first time requested, including in the cache.\n", item) + + if e := c.init(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while adding the new item [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects cached"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects cached"}).Inc() + + return o, nil + + } + + l.Trace.Printf("[CACHE] Object [ %v ] exists in the cache.\n", item) + + c.store.mutex.Lock() + + diff := (time.Now()).Sub(c.store.data[item].lastUpdate) + + c.store.mutex.Unlock() + + if diff <= c.duration { + + l.Trace.Printf("[CACHE] Object [ %v ] cache hasn't expired yet.\n", item) + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return object.value, nil + + } + + l.Warning.Printf("[CACHE] Object [ %v ] cache has expired. Starting the upgrade.\n", item) + + if e := c.fetch(item, token); e != nil { + + l.Warning.Printf("[CACHE] Something went wrong while fetching the updated data for the object [ %v ] to the cache. Error: %v\n", item, e) + + c.metrics.With(prometheus.Labels{"state": "FAIL", "resource": "Total objects refreshed"}).Inc() + + return nil, e + + } + + l.Trace.Printf("[CACHE] Object [ %v ] updated retrieved from the cache.\n", item) + + c.store.mutex.RLock() + + o := c.store.data[item].value + + c.store.mutex.RUnlock() + + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects refreshed"}).Inc() + c.metrics.With(prometheus.Labels{"state": "OK", "resource": "Total objects retrieved from cache"}).Inc() + + return o, nil + +} diff --git a/services/udr/server/config.go b/services/udr/server/config.go new file mode 100644 index 0000000..4eb0cf9 --- /dev/null +++ b/services/udr/server/config.go @@ -0,0 +1,223 @@ +package main + +import ( + "encoding/json" + "strings" + + "github.com/spf13/viper" + l "gitlab.com/cyclops-utilities/logging" +) + +// The following structs: apikey, dbConfig, eventsConfig, generalConfig, +// kafkaConfig, and keycloakConfig are part of the configuration struct which +// acts as the main reference for configuration parameters in the system. +type apiKey struct { + Enabled bool `json:"enabled"` + Key string + Place string + Token string `json:"token"` +} + +type configuration struct { + APIKey apiKey + DB dbConfig + Events eventsConfig + General generalConfig + Kafka kafkaConfig + Keycloak keycloakConfig `json:"keycloak"` + DefaultPlans map[string]string + Prometheus prometheusConfig +} + +type dbConfig struct { + CacheRetention string + DbName string + Host string + Password string + Port int + SSLMode string + Username string +} + +type eventsConfig struct { + Filters []string +} + +type generalConfig struct { + CertificateFile string `json:"certificate_file"` + CertificateKey string `json:"certificate_key"` + CORSEnabled bool + CORSHeaders []string + CORSMethods []string + CORSOrigins []string + HTTPSEnabled bool + InsecureSkipVerify bool + LogFile string + LogLevel string + LogToConsole bool + ServerPort int + Services map[string]string +} + +type kafkaConfig struct { + Brokers []string + MaxBytes int + MinBytes int + Offset int64 + Partition int + TopicsIn []string + TopicsOut []string + TLSEnabled bool +} + +type keycloakConfig struct { + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Enabled bool `json:"enabled"` + Host string `json:"host"` + Port int `json:"port"` + Realm string `json:"realm"` + RedirectURL string `json:"redirect_url"` + UseHTTP bool `json:"use_http"` +} + +type planConfig struct { + Default string +} +type prometheusConfig struct { + Host string + MetricsExport bool + MetricsPort string + MetricsRoute string +} + +// dumpConfig 's job is to dumps the configuration in JSON format to the log +// system. It makes use of the masking function to keep some secrecy in the log. +// Parameters: +// - c: configuration type containing the config present in the system. +func dumpConfig(c configuration) { + cfgCopy := c + + // deal with configuration params that should be masked + cfgCopy.APIKey.Token = masked(c.APIKey.Token, 4) + cfgCopy.DB.Password = masked(c.DB.Password, 4) + cfgCopy.Keycloak.ClientSecret = masked(c.Keycloak.ClientSecret, 4) + + // mmrshalindent creates a string containing newlines; each line starts with + // two spaces and two spaces are added for each indent... + configJSON, _ := json.MarshalIndent(cfgCopy, " ", " ") + + l.Info.Printf("[CONFIG] Configuration settings:\n") + + l.Info.Printf("%v\n", string(configJSON)) + +} + +// masked 's job is to return asterisks in place of the characters in a +// string with the exception of the last indicated. +// Parameters: +// - s: string to be masked +// - unmaskedChars: int with the amount (counting from the end of the string) of +// characters to keep unmasked. +// Returns: +// - returnString: the s string passed as parameter masked. +func masked(s string, unmaskedChars int) (returnString string) { + + if len(s) <= unmaskedChars { + + returnString = s + + return + + } + + asteriskString := strings.Repeat("*", (len(s) - unmaskedChars)) + + returnString = asteriskString + string(s[len(s)-unmaskedChars:]) + + return + +} + +// parseConfig handles the filling of the config struct with the data Viper gets +// from the configuration file. +// Returns: +// - c: the configuration struct filled with the relevant parsed configuration. +func parseConfig() (c configuration) { + + l.Trace.Printf("[CONFIG] Retrieving configuration.\n") + + c = configuration{ + + APIKey: apiKey{ + Enabled: viper.GetBool("apikey.enabled"), + Key: viper.GetString("apikey.key"), + Place: viper.GetString("apikey.place"), + Token: viper.GetString("apikey.token"), + }, + + DB: dbConfig{ + CacheRetention: viper.GetString("database.cacheretention"), + DbName: viper.GetString("database.dbname"), + Host: viper.GetString("database.host"), + Password: viper.GetString("database.password"), + Port: viper.GetInt("database.port"), + SSLMode: viper.GetString("database.sslmode"), + Username: viper.GetString("database.username"), + }, + + Events: eventsConfig{ + Filters: viper.GetStringSlice("events.filters"), + }, + + General: generalConfig{ + CertificateFile: viper.GetString("general.certificatefile"), + CertificateKey: viper.GetString("general.certificatekey"), + CORSEnabled: viper.GetBool("general.corsenabled"), + CORSHeaders: viper.GetStringSlice("general.corsheaders"), + CORSMethods: viper.GetStringSlice("general.corsmethods"), + CORSOrigins: viper.GetStringSlice("general.corsorigins"), + HTTPSEnabled: viper.GetBool("general.httpsenabled"), + InsecureSkipVerify: viper.GetBool("general.insecureskipverify"), + LogFile: viper.GetString("general.logfile"), + LogLevel: viper.GetString("general.loglevel"), + LogToConsole: viper.GetBool("general.logtoconsole"), + ServerPort: viper.GetInt("general.serverport"), + Services: viper.GetStringMapString("general.services"), + }, + + Kafka: kafkaConfig{ + Brokers: viper.GetStringSlice("kafka.brokers"), + MaxBytes: viper.GetInt("kafka.sizemax"), + MinBytes: viper.GetInt("kafka.sizemin"), + Offset: viper.GetInt64("kafka.offset"), + Partition: viper.GetInt("kafka.partition"), + TopicsIn: viper.GetStringSlice("kafka." + service + "in"), + TopicsOut: viper.GetStringSlice("kafka." + service + "out"), + TLSEnabled: viper.GetBool("kafka.tlsenabled"), + }, + + Keycloak: keycloakConfig{ + ClientID: viper.GetString("keycloak.clientid"), + ClientSecret: viper.GetString("keycloak.clientsecret"), + Enabled: viper.GetBool("keycloak.enabled"), + Host: viper.GetString("keycloak.host"), + Port: viper.GetInt("keycloak.port"), + Realm: viper.GetString("keycloak.realm"), + RedirectURL: viper.GetString("keycloak.redirecturl"), + UseHTTP: viper.GetBool("keycloak.usehttp"), + }, + + DefaultPlans: viper.GetStringMapString("plans"), + + Prometheus: prometheusConfig{ + Host: viper.GetString("prometheus.host"), + MetricsExport: viper.GetBool("prometheus.metricsexport"), + MetricsPort: viper.GetString("prometheus.metricsport"), + MetricsRoute: viper.GetString("prometheus.metricsroute"), + }, + } + + return + +} diff --git a/services/udr/server/dbManager/dbManager.go b/services/udr/server/dbManager/dbManager.go new file mode 100644 index 0000000..e2fd2f3 --- /dev/null +++ b/services/udr/server/dbManager/dbManager.go @@ -0,0 +1,540 @@ +package dbManager + +import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/cacheManager" + l "gitlab.com/cyclops-utilities/logging" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +const ( + statusDuplicated = iota + statusFail + statusMissing + statusOK +) + +// DbParameter is the struct defined to group and contain all the methods +// that interact with the database. +// On it there is the following parameters: +// - Cache: CacheManager pointer for the cache mechanism. +// - connStr: strings with the connection information to the database +// - Db: a gorm.DB pointer to the db to invoke all the db methods +type DbParameter struct { + Cache *cacheManager.CacheManager + connStr string + Db *gorm.DB + Metrics map[string]*prometheus.GaugeVec +} + +// New is the function to create the struct DbParameter. +// Parameters: +// - dbConn: strings with the connection information to the database +// - tables: array of interfaces that will contains the models to migrate +// to the database on initialization +// Returns: +// - DbParameter: struct to interact with dbManager functionalities¬ +func New(dbConn string, tables ...interface{}) *DbParameter { + + l.Trace.Printf("[DB] Gerenating new DBParameter.\n") + + var ( + dp DbParameter + err error + ) + + dp.connStr = dbConn + + dp.Db, err = gorm.Open(postgres.Open(dbConn), &gorm.Config{}) + + if err != nil { + + l.Error.Printf("[DB] Error opening connection. Error: %v\n", err) + + panic(err) + + } + + l.Trace.Printf("[DB] Migrating tables.\n") + + //Database migration, it handles everything + dp.Db.AutoMigrate(tables...) + + l.Trace.Printf("[DB] Generating hypertables.\n") + + // Hypertables creation for timescaledb in case of needed + dp.Db.Exec("SELECT create_hypertable('" + dp.Db.NamingStrategy.TableName("Usage") + "', 'timedate');") + + return &dp + +} + +// AddMetric tries to insert a given new metric in the system, checking and +// reporting if it's already exists in the system. +// Parameters: +// - metric: string with the new metric to add to the system. +// Returns: +// - error in case of duplication or failure in the task. +func (d *DbParameter) AddMetric(metric string) error { + + l.Trace.Printf("[DB] Attempting to add a new metric [ %v ] to the system.\n", metric) + + m := models.Metric{Metric: metric} + + if e := d.Db.Where(&m).First(&models.Metric{}).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + e := d.Db.Create(&m).Error + + if e != nil { + + l.Warning.Printf("[DB] There were an problem adding the metric [ %v ] to the system. Error: %v\n", metric, e) + + } else { + + d.Metrics["count"].With(prometheus.Labels{"type": "Usage metrics added"}).Inc() + + l.Debug.Printf("[DB] Metric [ %v ] added to the system.\n", metric) + + } + + return e + + } + + l.Debug.Printf("[DB] The metric [ %v ] already exists in the system.\n", metric) + + return nil + +} + +// AddRecord job is to add a compacted record for a 8h interval in the system. +// Parameters: +// - report: a UDRRecord containing the Usage received and compacted. +// Returns: +// - error in case of duplication or failure in the task. +func (d *DbParameter) AddRecord(report models.UDRRecord) (e error) { + + l.Trace.Printf("[DB] Attempting to add a new compacted UDR Record in the system.\n") + + var reportUpdate models.UDRRecord + + reportCheck := models.UDRRecord{ + AccountID: report.AccountID, + Metadata: report.Metadata, + TimeTo: report.TimeTo, + TimeFrom: report.TimeFrom, + ResourceID: report.ResourceID, + ResourceName: report.ResourceName, + ResourceType: report.ResourceType, + } + + e = d.Db.Where(&reportCheck).First(&reportUpdate).Error + + if errors.Is(e, gorm.ErrRecordNotFound) { + + e = d.Db.Create(&report).Error + + if e == nil { + + d.Metrics["count"].With(prometheus.Labels{"type": "UDR Records added"}).Inc() + + l.Trace.Printf("[DB] New UDR Record added in the system.\n") + + return + + } + + l.Trace.Printf("[DB] Something went wrong when adding a new UDR Record to the system. Error: %v\n", e) + + return + + } + + l.Trace.Printf("[DB] The UDR Record [ %v ] is already in the system, attempt to update it...\n", reportUpdate) + + e = d.Db.Model(&reportUpdate).Updates(&report).Error + + if e == nil { + + d.Metrics["count"].With(prometheus.Labels{"type": "UDR Records updated"}).Inc() + + l.Trace.Printf("[DB] UDR Record updated in the system.\n") + + return + + } + + l.Trace.Printf("[DB] Something went wrong when updating the existing UDR Record to the system. Error: %v\n", e) + + return + +} + +// AddReport job is to add a new report of compacted usage to the system. +// Parameters: +// - report: a Report containing the data to be added to the system. +// Returns: +// - error in case of duplication or failure in the task. +func (d *DbParameter) AddReport(report models.UReport) (e error) { + + l.Trace.Printf("[DB] Attempting to add a new usage report to the system.\n") + + if e = d.Db.Where(&report).First(&models.UReport{}).Error; errors.Is(e, gorm.ErrRecordNotFound) { + + e = d.Db.Create(&report).Error + + if e == nil { + + d.Metrics["count"].With(prometheus.Labels{"type": "UDR Reports added"}).Inc() + + l.Trace.Printf("[DB] New usage report added in the system.\n") + + } else { + + l.Trace.Printf("[DB] Something went wrong when adding a new usage report to the system. Error: %v\n", e) + + } + + return e + + } + + return nil + +} + +// GetAccounts job is to retrieve a list of the accounts in the system. +// Returns: +// - Slice of strings containing the accounts in the system with usage data. +func (d *DbParameter) GetAccounts() []string { + + l.Trace.Printf("[DB] Attempting to retrieve the account list in the system.\n") + + type scann struct { + Account string + } + + var accounts []string + var acc []scann + + if e := d.Db.Debug().Raw("SELECT DISTINCT " + d.Db.NamingStrategy.ColumnName("", "Account") + " FROM " + d.Db.NamingStrategy.TableName("Usage")).Scan(&acc).Error; e == nil { + + for i := range acc { + + accounts = append(accounts, acc[i].Account) + + } + + l.Trace.Printf("[DB] [ %v ] accounts were retrieved from the system.\n", len(accounts)) + + } else { + + l.Warning.Printf("[DB] Something went wrong while retrieving the accounts in the system. Error: %v\n", e) + + } + + return accounts + +} + +// GetUDRAccounts job is to retrieve a list of the accounts in the system that +// have a UDR Report ready to be sent. +// Returns: +// - Slice of strings containing the accounts in the system with UDR Reports. +func (d *DbParameter) GetUDRAccounts() []string { + + l.Trace.Printf("[DB] Attempting to retrieve the account list in the system.\n") + + type scann struct { + AccountID string + } + + var accounts []string + var acc []scann + + if e := d.Db.Debug().Raw("SELECT DISTINCT " + d.Db.NamingStrategy.ColumnName("", "AccountID") + " FROM " + d.Db.NamingStrategy.TableName("UDRRecord")).Scan(&acc).Error; e == nil { + + for i := range acc { + + accounts = append(accounts, acc[i].AccountID) + + } + + l.Trace.Printf("[DB] [ %v ] accounts were retrieved from the system.\n", len(accounts)) + + } else { + + l.Warning.Printf("[DB] Something went wrong while retrieving the accounts in the system. Error: %v\n", e) + + } + + return accounts + +} + +// GetInterval job is to provide a proper query string to use in GORM to indicate +// a range of time. +// Parameters: +// - field: a string with the db field to use for the time-window. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - s: the ready for query string with the data provided. +func (d *DbParameter) GetInterval(field string, from strfmt.DateTime, to strfmt.DateTime) (s string) { + + l.Trace.Printf("[DB] Attempting to get an interval for a db query.\n") + + s = fmt.Sprintf("%v >= '%v' AND %v <= '%v'", field, from, field, to) + + return + +} + +// GetMetrics job is to retrieve the list of metrics registered in the system. +// Returns: +// - a slice of references with the metrics in the system. +// - error in case of duplication or failure in the task. +func (d *DbParameter) GetMetrics() ([]*models.Metric, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the metrics in the system.\n") + + var m []*models.Metric + var e error + + if e = d.Db.Debug().Find(&m).Error; e == nil { + + l.Debug.Printf("[DB] [%v] metrics retrieved from the system.\n", len(m)) + + } else { + + l.Warning.Printf("[DB] Something went wrong while retrieving metrics from the system. Error: %v\n", e) + + } + + return m, e + +} + +// GetRecords job is to retrieve the non-compacted usage records from the system +// in the requested time-window with the posibility of filter by metric. +// Parameters: +// - metric: a string with the metric to filter the records. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a slice of references with the usage contained in the system within the +// requested time-window. +func (d *DbParameter) GetRecords(metric string, from strfmt.DateTime, to strfmt.DateTime) []*models.Usage { + + l.Trace.Printf("[DB] Attempting to retrieve the non-compacted usage records.\n") + + var u []*models.Usage + + interval := d.GetInterval("timedate", from, to) + + if e := d.Db.Where(interval).Where(&models.Usage{ResourceType: metric}).Find(&u).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the non-compacted usage records from the system. Error: %v\n", e) + + } else { + + l.Debug.Printf("[DB] [ %v ] non-compacted usage records retrieved from the system.\n", len(u)) + + } + + return u + +} + +// GetReport job is to retrieve the compacted usage records from the system for +// the provided account in the requested time-window with the posibility of +// filter by metric. +// Parameters: +// - id: string containing the id of the account requested. +// - metric: a string with the metric to filter the records. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a slice of references with the usage contained in the system within the +// requested time-window. +func (d *DbParameter) GetReport(id, metric string, from, to strfmt.DateTime) []*models.UDRReport { + + l.Trace.Printf("[DB] Attempting to retrieve the compacted usage records.\n") + + var r []*models.UDRReport + var u models.UDRRecord + + window := d.getWindow(from, to) + + if id != "" { + + u.AccountID = id + + } + + if metric != "" { + + u.ResourceType = metric + + } + + if e := d.Db.Where(window).Where(&u).Find(&models.UDRRecord{}).Scan(&r).Error; e != nil { + + l.Warning.Printf("[DB] Something went wrong while retrieving the compacted usage records from the system. Error: %v\n", e) + + } else { + + l.Debug.Printf("[DB] [ %v ] compacted usage records retrieved from the system.\n", len(r)) + + } + + return r + +} + +// GetUsage job is to retrieve the usage report of the system or the specified +// account within the requested time-window with the posibility to filter by +// metric. +// Parameters: +// - id: string containing the id of the account requested. +// - metric: a string with the metric to filter the records. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a slice of references with the usage report contained in the system within +// the requested time-window. +// - error in case of duplication or failure in the task. +func (d *DbParameter) GetUsage(id, metric string, from, to strfmt.DateTime) ([]*models.UReport, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the usage report from the system.\n") + + var r []*models.UReport + var r0 models.UReport + var e error + + window := d.getWindow(from, to) + + if id != "" { + + r0.AccountID = id + + } + + e = d.Db.Where(window).Where(&r0).Find(&r).Error + + if e == nil { + + for idx := range r { + + r[idx].Usage = d.GetReport(r[idx].AccountID, metric, r[idx].TimeFrom, r[idx].TimeTo) + + } + + l.Debug.Printf("[DB] [ %v ] Usage reports retrieved from the system.\n", len(r)) + + } else { + + l.Warning.Printf("[DB] Something went wrong while retrieving the usage reports from the system. Error: %v\n", e) + + } + + return r, e + +} + +// GetUsages job is to retrieve the usage report of the system or the specified +// account accounts within the requested time-window with the posibility to +// filter by metric. +// Parameters: +// - ids: string containing the list of ids of the accounts requested. +// - metric: a string with the metric to filter the records. +// - from: a datatime reference for the initial border of the time-window. +// - to: a datatime reference for the final border of the time-window. +// Returns: +// - a slice of references with the usage report contained in the system within +// the requested time-window. +// - error in case of duplication or failure in the task. +func (d *DbParameter) GetUsages(ids, metric string, from, to strfmt.DateTime) ([]*models.UReport, error) { + + l.Trace.Printf("[DB] Attempting to retrieve the usage report from the system.\n") + + var total, r []*models.UReport + var r0 models.UReport + var e error + + window := d.getWindow(from, to) + + list := strings.Split(ids, ",") + + for _, acc := range list { + + r0.AccountID = acc + + if e = d.Db.Where(window).Where(&r0).Find(&r).Error; e == nil { + + for idx := range r { + + r[idx].Usage = d.GetReport(r[idx].AccountID, metric, r[idx].TimeFrom, r[idx].TimeTo) + + } + + l.Debug.Printf("[DB] [ %v ] Usage reports retrieved from the system.\n", len(r)) + + } else { + + l.Warning.Printf("[DB] Something went wrong while retrieving the usage reports from the system. Error: %v\n", e) + + } + + total = append(total, r...) + + } + + return total, e + +} + +// getWindow job is to select the timeframe for the usage retrievals according +// to the data providad from= '%v'", d.Db.NamingStrategy.ColumnName("", "TimeFrom"), from) + + } else { + + s = fmt.Sprintf("%v >= '%v' AND %v <= '%v'", d.Db.NamingStrategy.ColumnName("", "TimeFrom"), from, d.Db.NamingStrategy.ColumnName("", "TimeTo"), to) + + } + + } else { + + if !((time.Time)(to)).IsZero() { + + s = fmt.Sprintf("%v <= '%v'", d.Db.NamingStrategy.ColumnName("", "TimeTo"), to) + + } + + } + + return s + +} diff --git a/services/udr/server/kafka.go b/services/udr/server/kafka.go new file mode 100644 index 0000000..0efe2c8 --- /dev/null +++ b/services/udr/server/kafka.go @@ -0,0 +1,311 @@ +package main + +import ( + "context" + "crypto/tls" + "reflect" + "strconv" + "time" + + "github.com/remeh/sizedwaitgroup" + "github.com/segmentio/encoding/json" + + "github.com/prometheus/client_golang/prometheus" + kafka "github.com/segmentio/kafka-go" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +type kafkaFunction func(*dbManager.DbParameter, interface{}) error + +type kafkaHandlerConf struct { + in []kafkaPackage + out []kafkaPackage +} + +type kafkaPackage struct { + topic string + partition int + model interface{} + function kafkaFunction + channel chan interface{} + saveDB bool +} + +// kafkaHandler job is to check the config that it receives and initialize the +// go rutines necesaries to satisfay the configuration it receives. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - kH: kafkaHandlerConf struct with the specific configuration used by the +// service. +func kafkaHandler(db *dbManager.DbParameter, monit *statusManager.StatusManager, kH kafkaHandlerConf) { + + l.Trace.Printf("[KAFKA] Initializing the receivers/senders according to the provided configuration.\n") + + if kH.in != nil { + + monit.InitEndpoint("kafka-receiver") + + for _, p := range kH.in { + + go kafkaReceiver(db, monit, p.topic, p.partition, p.model, p.function, p.saveDB) + + } + } + + if kH.out != nil { + + monit.InitEndpoint("kafka-sender") + + for _, p := range kH.out { + + go kafkaSender(db, monit, p.topic, p.partition, p.channel) + + } + + } +} + +// kafkaReceiver is the abstracted interface used to receive JSON data from kafka. +// The functions assumes that by default anything that comes from the kafka topic +// and validates against a specific data model has to be added to the db. +// Besides that it has the option to call an external function to interact with +// the data before putting it in the db. +// Parameters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - m: model to validate data against. +// - f: optional external function for more functionality. +// - saveDB: bool to control is the received data needs to be saved in the db. +func kafkaReceiver(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, m interface{}, f kafkaFunction, saveDB bool) { + + l.Trace.Printf("[KAFKA] Initializing kafka receiver for topic: %v.\n", t) + + conf := kafka.ReaderConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Partition: p, + MinBytes: cfg.Kafka.MinBytes, + MaxBytes: cfg.Kafka.MaxBytes, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + r := kafka.NewReader(conf) + defer r.Close() + + if e := r.SetOffset(cfg.Kafka.Offset); e != nil { + + l.Warning.Printf("[KAFKA] There was a problem when setting the offset, stopping the kafka handler NOW. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream offset"}).Inc() + + return + + } + + swg := sizedwaitgroup.New(8) + + for { + + rm, e := r.ReadMessage(context.Background()) + + if e != nil { + + l.Warning.Printf("[KAFKA] Error detected in the kafka stream. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream"}).Inc() + + continue + + } + + // Goroutines start + swg.Add() + go func() { + + callTime := time.Now() + monit.APIHit("kafka-receiver", callTime) + + defer swg.Done() + + o := reflect.New(reflect.TypeOf(m)).Interface() + + if e := json.Unmarshal(rm.Value, &o); e == nil { + + l.Info.Printf("[KAFKA] Relevant information detected in the stream: Topic: %v, partition: %v.\n", t, p) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object received"}).Inc() + + if f != nil { + + l.Info.Printf("[KAFKA] Function for specialized work detected. Starting its processing.\n") + + if err := f(db, o); err != nil { + + l.Warning.Printf("[KAFKA] There was a problem processing the model's specific function. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: linked function"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: linked function"}).Inc() + + } + + } + + if saveDB { + + l.Info.Printf("[KAFKA] Saving procesed record in the database.\n") + + if err := db.Db.Create(o).Error; err != nil { + + l.Warning.Printf("[KAFKA] There was a problem adding the record into the database. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: db saving"}).Inc() + + } else { + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "OK: object db saved"}).Inc() + + } + + } + + } else { + + l.Warning.Printf("[KAFKA] The information in the stream does not fit the expected model, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "RECEIVER", "topic": t, "state": "FAIL: stream-rubish"}).Inc() + + } + + monit.APIHitDone("kafka-receiver", callTime) + + }() + + } + +} + +// kafkaSender is the abstracted interface handling the sending of data through +// kafka topics. +// Paramenters: +// - db: DbParameter to direct interaction with the database. +// - monit: statusManager parameter to interact with statusManager subsystem. +// - t: string containing the kafka-topic in use. +// - p: int containing the kafka-topic partition. +// - c: interface{} channel to receive the data that will be marshalled into +// JSON and then transmitted via kafka. +func kafkaSender(db *dbManager.DbParameter, monit *statusManager.StatusManager, t string, p int, c chan interface{}) { + + l.Trace.Printf("[KAFKA] Initializing kafka sender for topic: %v.\n", t) + + conf := kafka.WriterConfig{ + Brokers: cfg.Kafka.Brokers, + Topic: t, + Balancer: &kafka.LeastBytes{}, + } + + if cfg.Kafka.TLSEnabled { + + dialer := &kafka.Dialer{ + Timeout: 10 * time.Second, + DualStack: true, + TLS: &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + InsecureSkipVerify: cfg.General.InsecureSkipVerify, + }, + } + + conf.Dialer = dialer + + } + + w := kafka.NewWriter(conf) + + defer w.Close() + + for { + + v, ok := <-c + + if !ok { + + l.Info.Printf("[KAFKA] The channel has problems or has been closed.\n") + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: channel"}).Inc() + + break + + } + + go func() { + + m, e := json.Marshal(&v) + + if e == nil { + + callTime := time.Now() + monit.APIHit("kafka-sender", callTime) + + l.Info.Printf("[KAFKA] Object received through the channel. Starting its processing.\n") + + err := w.WriteMessages(context.Background(), + kafka.Message{ + Key: []byte(t + "-" + strconv.Itoa(p)), + Value: m, + }, + ) + + if err != nil { + + l.Warning.Printf("[KAFKA] There was a problem when sending the record through the stream. Error: %v\n", err) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: stream"}).Inc() + + } else { + + l.Info.Printf("[KAFKA] Object added to the stream succesfully. Topic: %v.\n", t) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "OK: object sent"}).Inc() + + } + + monit.APIHitDone("kafka-sender", callTime) + + } else { + + l.Warning.Printf("[KAFKA] The information to be sent into the stream cannot be marshalled, please check with the administrator. Error: %v\n", e) + + db.Metrics["kafka"].With(prometheus.Labels{"mode": "SENDER", "topic": t, "state": "FAIL: JSON Marshalling"}).Inc() + + } + + }() + + } + +} diff --git a/services/udr/server/main.go b/services/udr/server/main.go new file mode 100644 index 0000000..976eb74 --- /dev/null +++ b/services/udr/server/main.go @@ -0,0 +1,176 @@ +package main + +import ( + "crypto/tls" + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/spf13/viper" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + cfg configuration + version string + service string +) + +// dbStart handles the initialization of the dbManager returning a pointer to +// the DbParameter to be able to use the dbManager methods. +// Parameters: +// - models: variadic interface{} containing all the models that need to be +// migrated to the db. +// Returns: +// - DbParameter reference. +func dbStart(models ...interface{}) *dbManager.DbParameter { + + connStr := "user=" + cfg.DB.Username + " password=" + cfg.DB.Password + + " dbname=" + cfg.DB.DbName + " sslmode=" + cfg.DB.SSLMode + + " host=" + cfg.DB.Host + " port=" + strconv.Itoa(cfg.DB.Port) + + return dbManager.New(connStr, models...) + +} + +// getBasePath function is to get the base URL of the server. +// Returns: +// - String with the value of the base URL of the server. +func getBasePath() string { + + type jsonBasePath struct { + BasePath string + } + + bp := jsonBasePath{} + + e := json.Unmarshal(restapi.SwaggerJSON, &bp) + + if e != nil { + + l.Warning.Printf("[MAIN] Unmarshalling of the basepath failed: %v\n", e) + + } + + return bp.BasePath + +} + +func init() { + + confFile := flag.String("conf", "./config", "configuration file path (without toml extension)") + + flag.Parse() + + //placeholder code as the default value will ensure this situation will never arise + if len(*confFile) == 0 { + + fmt.Printf("Usage: %v -conf=/path/to/configuration/file\n", strings.Title(service)) + + os.Exit(0) + + } + + // err := gcfg.ReadFileInto(&cfg, *confFile) + viper.SetConfigName(*confFile) // name of config file (without extension) + viper.SetConfigType("toml") + viper.AddConfigPath(".") // path to look for the config file in + + err := viper.ReadInConfig() // Find and read the config file + + if err != nil { + + // TODO(murp) - differentiate between file not found and formatting error in + // config file) + fmt.Printf("[MAIN] Failed to parse configuration data: %v\nCorrect usage: %v -conf=/path/to/configuration/file\n", err, strings.Title(service)) + + os.Exit(1) + + } + + cfg = parseConfig() + + e := l.InitLogger(cfg.General.LogFile, cfg.General.LogLevel, cfg.General.LogToConsole) + + if e != nil { + + fmt.Printf("[MAIN] Initialization of the logger failed. Error: %v\n", e) + + } + + l.Info.Printf("Cyclops Labs %v Manager version %v initialized\n", strings.Title(service), version) + + dumpConfig(cfg) + +} + +func main() { + + //Getting the service handler and prometheus register + h, r, e := getService() + + if e != nil { + + log.Fatal(e) + + } + + if cfg.Prometheus.MetricsExport { + + l.Info.Printf("[MAIN] Starting to serve Prometheus Metrics, access server on https://localhost:%v/%v\n", cfg.Prometheus.MetricsPort, cfg.Prometheus.MetricsRoute) + + go func() { + + http.Handle(cfg.Prometheus.MetricsRoute, promhttp.HandlerFor(r, promhttp.HandlerOpts{})) + + log.Fatal(http.ListenAndServe(":"+cfg.Prometheus.MetricsPort, nil)) + + }() + + } + + serviceLocation := ":" + strconv.Itoa(cfg.General.ServerPort) + + if cfg.General.HTTPSEnabled { + + c := &tls.Config{ + MinVersion: tls.VersionTLS12, + CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256}, + PreferServerCipherSuites: true, + } + + srv := &http.Server{ + Addr: serviceLocation, + Handler: h, + TLSConfig: c, + TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0), + } + + l.Info.Printf("[MAIN] Starting to serve %v, access server on https://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTPS) start time"}).Set(float64(time.Now().Unix())) + + log.Fatal(srv.ListenAndServeTLS(cfg.General.CertificateFile, cfg.General.CertificateKey)) + + } else { + + l.Info.Printf("[MAIN] Starting to serve %v, access server on http://localhost%v\n", strings.Title(service), serviceLocation) + + metricTime.With(prometheus.Labels{"type": "Service (HTTP) start time"}).Set(float64(time.Now().Unix())) + + // Run the standard http server + log.Fatal(http.ListenAndServe(serviceLocation, h)) + + } + +} diff --git a/services/udr/server/metrics.go b/services/udr/server/metrics.go new file mode 100644 index 0000000..f7a13d4 --- /dev/null +++ b/services/udr/server/metrics.go @@ -0,0 +1,112 @@ +package main + +import ( + "strings" + + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +var ( + metricTime *prometheus.GaugeVec + metricSecurity *prometheus.GaugeVec +) + +func prometheusStart() (metricsMap map[string]*prometheus.GaugeVec, register *prometheus.Registry) { + + l.Trace.Printf("[PROMETHEUS] Intializing metrics for the service\n") + + metricsMap = make(map[string]*prometheus.GaugeVec) + register = prometheus.NewPedanticRegistry() + + metricCache := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "cache_state", + Help: "Different cache metrics of fails and usages", + }, + []string{ + "state", + "resource", + }, + ) + + metricCount := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processed_count", + Help: "Different counting metrics for processed tasks", + }, + []string{ + "type", + }, + ) + + metricEndpoint := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "api_request", + Help: "Different countings metrics for the endpoints", + }, + []string{ + "code", + "method", + "route", + }, + ) + + metricKafka := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "kafka_state", + Help: "Different Kafka metrics of fails and usage of topics", + }, + []string{ + "mode", + "state", + "topic", + }, + ) + + metricSecurity = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "access_control", + Help: "Different access control metrics", + }, + []string{ + "mode", + "state", + }, + ) + + metricTime = prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Namespace: "CYCLOPS", + Subsystem: strings.Split(service, "-")[0] + "_Service", + Name: "processing_time", + Help: "Different timing metrics", + }, + []string{ + "type", + }, + ) + + register.MustRegister(metricCache, metricCount, metricEndpoint, metricKafka, + metricSecurity, metricTime) + + metricsMap["cache"] = metricCache + metricsMap["count"] = metricCount + metricsMap["api"] = metricEndpoint + metricsMap["kafka"] = metricKafka + metricsMap["security"] = metricSecurity + metricsMap["time"] = metricTime + + return + +} diff --git a/services/udr/server/metricsManager/metricsManager.go b/services/udr/server/metricsManager/metricsManager.go new file mode 100644 index 0000000..5e838b5 --- /dev/null +++ b/services/udr/server/metricsManager/metricsManager.go @@ -0,0 +1,81 @@ +package metricsManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/metrics_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// MetricsManager is the struct defined to group and contain all the methods +// that interact with the Metrics endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type MetricsManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct MetricsManager that grant +// access to the methods to interact with the metrics endpoint. +// Parameters: +// - db: a reference to the DbParameter to be able to interact with the db methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// Returns: +// - ResellerManager: struct to interact with the metrics endpoint functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *MetricsManager { + + l.Trace.Printf("[MetricsManager] Generating new MetricsManager.\n") + + monit.InitEndpoint("metrics") + + return &MetricsManager{ + db: db, + monit: monit, + } + +} + +// GetMetrics (Swagger func) is the function behind the (GET) endpoint +// /metrics +// Its job is to provide a list of the metrics saved in the system that can be +// used for filtering the usage report. +func (m *MetricsManager) GetMetrics(ctx context.Context, params metrics_management.GetMetricsParams) middleware.Responder { + + l.Trace.Printf("[MetricsManager] GetMetrics endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("metrics", callTime) + + metrics, e := m.db.GetMetrics() + + if e == nil { + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/metrics"}).Inc() + + m.monit.APIHitDone("metrics", callTime) + + return metrics_management.NewGetMetricsOK().WithPayload(metrics) + + } + + s := "There was an error retrieving the Metrics from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/metrics"}).Inc() + + m.monit.APIHitDone("metrics", callTime) + + return metrics_management.NewGetMetricsInternalServerError().WithPayload(&errorReturn) + +} diff --git a/services/udr/server/security.go b/services/udr/server/security.go new file mode 100644 index 0000000..7b7cdb4 --- /dev/null +++ b/services/udr/server/security.go @@ -0,0 +1,232 @@ +package main + +import ( + "context" + "errors" + "strconv" + + "github.com/Nerzal/gocloak/v7" + "github.com/prometheus/client_golang/prometheus" + l "gitlab.com/cyclops-utilities/logging" +) + +type basicUserData struct { + UserSub string +} + +type userInfo struct { + Username string `json:"username"` + Firstname string `json:"firstname"` + Lastname string `json:"lastname"` + EmailAddress string `json:"email"` + EmailVerified bool `json:"emailverified"` + ID string `json:"id"` +} + +// AuthAPIKey (Swagger func) assures that the token provided when connecting to +// the API is the one presented in the config file as the valid token for the +// deployment. +func AuthAPIKey(token string) (i interface{}, e error) { + + l.Warning.Printf("[SECURITY] APIKey Authentication: Trying entry with token: %v\n", token) + + if !cfg.APIKey.Enabled { + + e = errors.New("the API Key authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "DISABLED"}).Inc() + + return + + } + + if cfg.APIKey.Token == token { + + i = basicUserData{ + UserSub: token, + } + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "ACCESS GRANTED"}).Inc() + + } else { + + e = errors.New("provided token is not valid") + + metricSecurity.With(prometheus.Labels{"mode": "APIKey", "state": "INVALID TOKEN"}).Inc() + + } + + return + +} + +// AuthKeycloak (Swagger func) is called whenever it is necessary to check if a +// token which is presented to access an API is valid. +// The functions assumes that in keycloak the roles are going to be in uppercase +// and in the form of SCOPE_ROLE. +// Example: +// ADMIN_ROLE <-> scope admin +func AuthKeycloak(token string, scopes []string) (i interface{}, returnErr error) { + + l.Debug.Printf("[SECURITY] AuthKeycloak: Performing authentication check - token = %v...%v\n", token, scopes) + + if !cfg.Keycloak.Enabled { + + returnErr = errors.New("the Keycloak authentication is not active in this deployment") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "DISABLED"}).Inc() + + return + + } + + keycloakService := getKeycloakService(cfg.Keycloak) + client := gocloak.NewClient(keycloakService) + + ctx := context.Background() + + _, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + // clientToken, err := client.LoginClient(ctx, cfg.Keycloak.ClientID, cfg.Keycloak.ClientSecret, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems logging in to keycloak. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to log in to keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable"}).Inc() + + return + + } + + u, err := client.GetUserInfo(ctx, token, cfg.Keycloak.Realm) + + if err != nil { + + l.Warning.Printf("[SECURITY] Problems getting user Info. Error: %v\n", err.Error()) + + returnErr = errors.New("unable to get userInfo from keycloak") + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "FAIL: Keycloak Server unavailable userInfo"}).Inc() + + return + + } + + if u != nil { + + i = basicUserData{ + UserSub: *u.Sub, + } + + metricSecurity.With(prometheus.Labels{"mode": "Keycloak", "state": "ACCESS GRANTED"}).Inc() + + } + + // userRoles := make(map[string]bool) + // + // roles, err := client.GetRoleMappingByUserID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to retrieve user roles from keycloak") + // + // return + // + // } + // + // for _, m := range roles.RealmMappings { + // + // userRoles[*m.Name] = true + // + // } + // + // ug, err := client.GetUserGroups(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *u.Sub) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting groups by user ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable to get user groups from keycloak") + // + // return + // + // } + // + // for _, m := range ug { + // + // roles, err := client.GetRoleMappingByGroupID(ctx, clientToken.AccessToken, cfg.Keycloak.Realm, *m.ID) + // + // if err != nil { + // + // l.Warning.Printf("[SECURITY] Problems getting roles by group ID. Error:\n" + err.Error()) + // + // returnErr = errors.New("unable get groups roles from keycloak") + // + // return + // + // } + // + // for _, n := range roles.RealmMappings { + // + // userRoles[*n.Name] = true + // + // } + // + // } + // + // control := false + // + // for _, sc := range scopes { + // + // if userRoles[strings.ToUpper(sc)+"_ROLE"] { + // + // control = true + // + // } + // + // } + // + // if !control { + // + // returnErr = errors2.New(401, "The required role is not present in the user permissions") + // + // return + // + // } + + return + +} + +// getKeycloaktService returns the keycloak service; note that there has to be exceptional +// handling of port 80 and port 443 +func getKeycloakService(c keycloakConfig) (s string) { + + if c.UseHTTP { + + s = "http://" + c.Host + + if c.Port != 80 { + + s = s + ":" + strconv.Itoa(c.Port) + } + + } else { + + s = "https://" + c.Host + + if c.Port != 443 { + + s = s + ":" + strconv.Itoa(c.Port) + + } + + } + + return + +} diff --git a/services/udr/server/service.go b/services/udr/server/service.go new file mode 100644 index 0000000..37ecd2d --- /dev/null +++ b/services/udr/server/service.go @@ -0,0 +1,153 @@ +package main + +import ( + "net/http" + "net/url" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" + eventsClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/metricsManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/statusManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/triggerManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/usageManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// getService is the uService instantiation function. A sample of the elements +// that need to be personalized for a new uService are provided. +// Returns: +// - hadler: return the http.handler with the swagger and (optionally) the CORS +// configured according to the config provided +// - e: in case of any error it's propagated to the invoker +func getService() (handler http.Handler, register *prometheus.Registry, e error) { + + l.Trace.Printf("[MAIN] Intializing service [ %v ] handler\n", strings.Title(service)) + + // TABLE0,...,N have to be customized + db := dbStart(&models.UReport{}, &models.UDRRecord{}, &models.Usage{}, &models.Metric{}) + mon := statusManager.New(db) + + // Prometheus Metrics linked to dbParameter + db.Metrics, register = prometheusStart() + + // cache linked to the dbParameter + db.Cache = cacheStart(db.Metrics["cache"]) + + // In case of needed, here is where kafka support is started + // The functions needs to be customized accordingly to the needs of the service + // And the parts of the service that might need to send messages need to get + // the channel + ch := kafkaStart(db, mon) + + //bp := getBasePath() + + eec := eventsClient.Config{ + URL: &url.URL{ + Host: cfg.General.Services["eventsengine"], + Path: eventsClient.DefaultBasePath, + Scheme: "http", + }, + AuthInfo: httptransport.APIKeyAuth(cfg.APIKey.Key, cfg.APIKey.Place, cfg.APIKey.Token), + } + + // Parts of the service HERE + m := metricsManager.New(db, mon) + u := usageManager.New(db, mon) + t := triggerManager.New(db, mon, eec, ch) + + // Initiate the http handler, with the objects that are implementing the business logic. + h, e := restapi.Handler(restapi.Config{ + StatusManagementAPI: mon, + TriggerManagementAPI: t, + MetricsManagementAPI: m, + UsageManagementAPI: u, + Logger: l.Info.Printf, + AuthKeycloak: AuthKeycloak, + AuthAPIKeyHeader: AuthAPIKey, + AuthAPIKeyParam: AuthAPIKey, + }) + + if e != nil { + + return + + } + + handler = h + + // CORS + if cfg.General.CORSEnabled { + + l.Trace.Printf("[MAIN] Enabling CORS for the service [ %v ]\n", strings.Title(service)) + + handler = cors.New( + cors.Options{ + Debug: (cfg.General.LogLevel == "DEBUG") || (cfg.General.LogLevel == "TRACE"), + AllowedOrigins: cfg.General.CORSOrigins, + AllowedHeaders: cfg.General.CORSHeaders, + AllowedMethods: cfg.General.CORSMethods, + }).Handler(h) + + } + + return + +} + +// kafkaStart handles the initialization of the kafka service. +// This is a sample function with the most basic usage of the kafka service, it +// should be redefined to match the needs of the service. +// Parameters: +// - db: DbPAramenter reference for interaction with the db. +// - mon: statusManager parameter reference to interact with the statusManager +// subsystem +// Returns: +// - ch: a interface{} channel to be able to send thing through the kafka topic generated. +func kafkaStart(db *dbManager.DbParameter, mon *statusManager.StatusManager) (ch chan interface{}) { + + l.Trace.Printf("[MAIN] Intializing Kafka\n") + + f := func(db *dbManager.DbParameter, model interface{}) (e error) { + + u := model.(*models.Usage) + + u.Timedate = strfmt.DateTime(time.Unix(u.Time, 0)) + + e = db.AddMetric(u.ResourceType) + + return + + } + + ch = make(chan interface{}) + + handler := kafkaHandlerConf{ + in: []kafkaPackage{ + { + topic: cfg.Kafka.TopicsIn[0], + model: models.Usage{}, + function: f, + saveDB: true, + }, + }, + out: []kafkaPackage{ + { + topic: cfg.Kafka.TopicsOut[0], + channel: ch, + }, + }, + } + + kafkaHandler(db, mon, handler) + + return + +} diff --git a/services/udr/server/statusManager/statusManager.go b/services/udr/server/statusManager/statusManager.go new file mode 100644 index 0000000..79f8b9b --- /dev/null +++ b/services/udr/server/statusManager/statusManager.go @@ -0,0 +1,325 @@ +package statusManager + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/status_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/dbManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// Array containing all the monitors in the subsystem with one monit per endpoint. +type monitor struct { + db map[string]*monits +} + +// monits or monitors, is a struct that contains the data about an API Endpoint +// tha is being monitored. +// Parameters: +// - last: string with the timestamp of the last update. +// - day: array for the 24h of the days containing the hits to the endpoint in +// during the last 24h. +// - BoT: int with the number of hits to the endpoint from the Beginning of Time, +// AKA since the service started. +type monits struct { + last string + day [24]int64 + BoT int64 + AvgTime float64 +} + +// StatusManager is the struct defined to group and contain all the methods +// that interact with the status report subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +type StatusManager struct { + db *dbManager.DbParameter +} + +var ( + mon monitor + start time.Time + avgTime map[string]int64 + mutex *sync.Mutex +) + +// New is the function to create the struct StatusManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// Returns: +// - StatusManager: struct to interact with statusManager subsystem functionalities. +func New(db *dbManager.DbParameter) *StatusManager { + + l.Trace.Printf("[StatusManager] Generating new StatusManager.\n") + + g := monits{last: "System just started"} + s := monits{last: "Status just started"} + + mon = monitor{ + db: make(map[string]*monits), + } + + mon.db["main"] = &g + mon.db["status"] = &s + + start = time.Now() + + avgTime = make(map[string]int64) + mutex = &sync.Mutex{} + + return &StatusManager{db: db} + +} + +// GetStatus (Swagger func) is the function behind the API Endpoint /status/{id} +// It give the current hit-status of the selected endpoint and a primitive +// system and db connection status report. +func (m *StatusManager) GetStatus(ctx context.Context, params status_management.GetStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] GetStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + if _, ok := mon.db[params.ID]; !ok { + + s := "The Status for the requested endpoint doesn't exists in the system." + missingReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "404", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusNotFound().WithPayload(&missingReturn) + + } + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db[params.ID].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db[params.ID].AvgTime, + DBState: statusDB, + LastRequest: mon.db[params.ID].last, + RequestsBoT: mon.db[params.ID].BoT, + RequestsLastHour: mon.db[params.ID].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status/" + params.ID}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewGetStatusOK().WithPayload(&stats) + +} + +// ShowStatus (Swagger func) is the function behind the API Endpoint /status +// It give the current hit-status of the whole system and a primitive +// system and db connection status report. +func (m *StatusManager) ShowStatus(ctx context.Context, params status_management.ShowStatusParams) middleware.Responder { + + l.Trace.Printf("[StatusManager] ShowStatus endpoint invoked.\n") + + callTime := time.Now() + m.APIHit("status", callTime) + + status := "Healthy" + statusDB := "UP" + + d, e := m.db.Db.DB() + + if err := d.Ping(); e != nil || err != nil { + + status = "Warning" + statusDB = "DOWN" + + } + + today := int64(0) + + for _, i := range mon.db["main"].day { + + today += i + + } + + stats := models.Status{ + AverageResponseTime: mon.db["main"].AvgTime, + DBState: statusDB, + LastRequest: mon.db["main"].last, + RequestsBoT: mon.db["main"].BoT, + RequestsLastHour: mon.db["main"].day[(time.Now()).Hour()], + RequestsToday: today, + SystemState: &status, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/status"}).Inc() + + m.APIHitDone("status", callTime) + + return status_management.NewShowStatusOK().WithPayload(&stats) + +} + +// InitEndpoint is meant to be called on the New() functions representing each +// endpoint, its job is to initialize the endpoint index in the status array. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +func (m *StatusManager) InitEndpoint(index string) { + + l.Trace.Printf("[StatusManager] Initializing monitoring of endpoint: %v.\n", index) + + e := monits{ + + last: index + " just started", + } + + mon.db[index] = &e + +} + +// APIHit is meant to be called at the beginning of each endpoint function. +// Its job is to update the information about the last time that endpoint was +// called and the rest of the metrics for the endpoint in the subsystem. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +func (m *StatusManager) APIHit(index string, t time.Time) { + + l.Debug.Printf("[StatusManager] Endpoint: %v, has been invoked.\n", index) + + limit, _ := time.ParseDuration("25h") + cleanAllLimit, _ := time.ParseDuration("26h") + difference := (time.Now()).Sub(start) + + if difference >= limit { + + if difference >= cleanAllLimit { + + m.cleanCount(25) + + } else { + + m.cleanCount(t.Hour() - 1) + + } + + start = time.Now() + + } + + // First we update the general count + mon.db["main"].last = t.String() + mon.db["main"].BoT++ + mon.db["main"].day[t.Hour()]++ + + // Then we update the specific endpoint count + mon.db[index].last = t.String() + mon.db[index].BoT++ + mon.db[index].day[t.Hour()]++ + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + avgTime[key] = t.UnixNano() + mutex.Unlock() + + return + +} + +// APIHit is meant to be called right before the return of each endpoint function. +// Its job is to update the average time spent on the processing of each endpoint. +// Parameters: +// - index: string for identifying the endpoint. Should be unique per endpoint +// and contained in the enum list in the swagger file +// - t: a time.Time timestamp with refering to the moment the endpoint was called. +// Returns: +// - key: the key for avgTime map track. +func (m *StatusManager) APIHitDone(index string, t time.Time) { + + key := fmt.Sprintf("%v_%v", index, t.UnixNano()) + + mutex.Lock() + previous, exists := avgTime[key] + mutex.Unlock() + + if exists { + + to := float64(time.Now().UnixNano()) + from := float64(previous) + + avg := float64((mon.db[index].AvgTime*float64(mon.db[index].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db[index].day[t.Hour()])) + avgSystem := float64((mon.db[index].AvgTime*float64(mon.db["main"].day[t.Hour()]-1) + (to-from)/float64(time.Millisecond)) / float64(mon.db["main"].day[t.Hour()])) + + mon.db[index].AvgTime = avg + mon.db["main"].AvgTime = avgSystem + + mutex.Lock() + delete(avgTime, key) + mutex.Unlock() + + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time for endpoint " + index}).Set(avg) + m.db.Metrics["time"].With(prometheus.Labels{"type": "Service average response time"}).Set(avgSystem) + + } + + return + +} + +// cleanCount 's job is to clean the day arrays on the subsystem. +// The logic behind it is that every 25h (or more) this function is called with +// a reference to previous hour cleaning setting the whole array to 0 except for +// that hour. +// Parameters: +// - h: integer for the hour to keep without cleaning. +func (m *StatusManager) cleanCount(h int) { + + for key := range mon.db { + + for idx := range mon.db[key].day { + + if idx != h { + + mon.db[key].day[idx] = 0 + + } + + } + + } + + return + +} diff --git a/services/udr/server/triggerManager/triggerManager.go b/services/udr/server/triggerManager/triggerManager.go new file mode 100644 index 0000000..437fae8 --- /dev/null +++ b/services/udr/server/triggerManager/triggerManager.go @@ -0,0 +1,561 @@ +package triggerManager + +import ( + "context" + "encoding/json" + "fmt" + "math" + "net/http" + "strings" + "time" + + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/remeh/sizedwaitgroup" + "gitlab.com/cyclops-utilities/datamodels" + eventsClient "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client" + eventsUsage "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/client/usage_management" + eeModels "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/eventsengine/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/trigger_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// TriggerManager is the struct defined to group and contain all the methods +// that interact with the trigger subsystem. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +// - eventsConfig: a EventsEngine client config reference to interact with EventsEngine +type TriggerManager struct { + pipe chan interface{} + db *dbManager.DbParameter + monit *statusManager.StatusManager + eventsConfig eventsClient.Config +} + +type CompactionKey struct { + Account string + ID string + Name string + Metadata string + Metric string + Unit string +} + +const ( + scaler = 1e7 +) + +// New is the function to create the struct TriggerManager. +// Parameters: +// - DbParameter: reference pointing to the DbParameter that allows the interaction +// with the DBManager methods. +// - StatusParameter: reference poining to the StatusManager that allows the +// interaction with the TriggerManager methods. +// - eventsClient.Config: a reference to the config needed to start the client +// interface to be able to interact with the EventsEngine service. +// Returns: +// - TriggerManager: struct to interact with triggerManager subsystem functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager, c eventsClient.Config, ch chan interface{}) *TriggerManager { + + l.Trace.Printf("[TriggerManager] Generating new TriggerManager.\n") + + monit.InitEndpoint("trigger") + + return &TriggerManager{ + pipe: ch, + db: db, + monit: monit, + eventsConfig: c, + } + +} + +func (m *TriggerManager) getClient(param *http.Request) *eventsClient.EventEngineManagementAPI { + + config := m.eventsConfig + + if len(param.Header.Get("Authorization")) > 0 { + + token := strings.Fields(param.Header.Get("Authorization"))[1] + + config.AuthInfo = httptransport.BearerToken(token) + + } + + r := eventsClient.New(config) + + return r + +} + +func (m *TriggerManager) getNiceFloat(i float64) (o float64) { + + return float64(math.Round(i*scaler) / scaler) + +} + +// ExecCompactation (Swagger func) is the function behind the (GET) endpoint +// /trigger/compact +// Its job is to generate a compactation of the information in the database +// by account, metrics and elements. +// It also extracts the usage from the EventsEngine and consolidates it with +// the UDRs already present in the system. +func (m *TriggerManager) ExecCompactation(ctx context.Context, params trigger_management.ExecCompactationParams) middleware.Responder { + + l.Trace.Printf("[TriggerManager] Compact endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("trigger", callTime) + + var from, to strfmt.DateTime + var accumErr []string + var udrCount int64 + var interval float64 + + queue := make(chan string, 1) + + now := time.Now() + records := make(map[string][]*models.Usage) + + if params.From != nil && params.To != nil { + + l.Trace.Printf("[TriggerManager] Preriod for compactation provided by params: [ %v ] to [ %v ].\n", params.From, params.To) + + from = *params.From + to = *params.To + + } else { + + if params.FastMode != nil && *params.FastMode { + + switch now.Minute() { + + case 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15: + + f := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 45, 0, 0, time.UTC) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, time.UTC)) + + from = strfmt.DateTime(f.Add(time.Minute * -60)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH(-1):45-HH:00 in day(-1?).\n") + + case 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 15, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH:00-HH:15.\n") + + case 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 15, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 30, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH:15-HH:30.\n") + + case 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 0: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 30, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 45, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: HH:30-HH:45.\n") + + } + + } else { + + switch now.Hour() { + + case 0, 1, 2, 3, 4, 5, 6, 7: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day()-1, 16, 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: 16:00-24:00 in day -1.\n") + + case 8, 9, 10, 11, 12, 13, 14, 15: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 8, 0, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: 00:00-08:00.\n") + + case 16, 17, 18, 19, 20, 21, 22, 23: + + from = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 8, 0, 0, 0, time.UTC)) + to = strfmt.DateTime(time.Date(now.Year(), now.Month(), now.Day(), 16, 0, 0, 0, time.UTC)) + + l.Trace.Printf("[TriggerManager] Preriod for compactation: 08:00-16:00.\n") + + } + + } + + } + + interval = float64(((time.Time)(to)).Sub((time.Time)(from)).Seconds()) + + // First we clean all the records so we always have a clean UDR generation + templateRecord := models.UDRRecord{ + TimeTo: to, + TimeFrom: from, + } + + l.Info.Printf("[TriggerManager] Clean up of previous UDRRecords started for period [ %v ] - [ %v ].\n", from, to) + + if e := m.db.Db.Where(&templateRecord).Delete(&models.UDRRecord{}).Error; e != nil { + + l.Warning.Printf("[TriggerManager] The clean up of previous UDRecords failed. Error: %v\n", e) + + } + + templateReport := models.UReport{ + TimeFrom: from, + TimeTo: to, + } + + l.Info.Printf("[TriggerManager] Clean up of previous UReports started for period [ %v ] - [ %v ].\n", from, to) + + if e := m.db.Db.Where(&templateReport).Delete(&models.UReport{}).Error; e != nil { + + l.Warning.Printf("[TriggerManager] The clean up of previous UReports failed. Error: %v\n", e) + + } + + // Handling all the error in the same place + go func() { + + for t := range queue { + accumErr = append(accumErr, t) + } + + }() + + // First we get the metric and accounts in the system. + metrics, _ := m.db.GetMetrics() + accounts := m.db.GetAccounts() + + // Then, we get all the records by metrics + for _, metric := range metrics { + + records[metric.Metric] = m.db.GetRecords(metric.Metric, from, to) + + } + + swg := sizedwaitgroup.New(8) + // Goroutines start + swg.Add() + go func() { + + defer swg.Done() + + // And finally, we compact the records by account + // Using the metadata as matching-key + for i := range accounts { + + swg.Add() + go func(acc string) { + + account := acc + defer swg.Done() + + for _, record := range records { + + accum := make(map[CompactionKey]float64) + counter := make(map[CompactionKey]float64) + metas := make(map[CompactionKey]datamodels.JSONdb) + + // In the first part we calculate the usage by metadata + // And create a map of metadatas/matching keys + for id := range record { + + if record[id].Account == account { + + key := CompactionKey{ + Account: record[id].Account, + ID: record[id].ResourceID, + Name: record[id].ResourceName, + Metadata: fmt.Sprintf("%v", record[id].Metadata), + Metric: record[id].ResourceType, + Unit: record[id].Unit, + } + + accum[key] += record[id].Usage + metas[key] = record[id].Metadata + counter[key]++ + + } + + } + + // In the second part we add the compacted records in the system + for key := range accum { + + use := datamodels.JSONdb{"used": accum[key] * interval / counter[key]} + unit := key.Unit + "(*period)" + + if v, exists := metas[key]["UDRMode"].(string); exists { + + switch v { + + case "avg": + + use = datamodels.JSONdb{"used": accum[key] / counter[key]} + unit = key.Unit + + case "sum": + + use = datamodels.JSONdb{"used": accum[key]} + unit = key.Unit + + default: + + use = datamodels.JSONdb{"used": accum[key] * interval / counter[key]} + unit = key.Unit + "(*period)" + + } + + } + + report := models.UDRRecord{ + AccountID: key.Account, + UsageBreakup: use, + Metadata: metas[key], + TimeTo: to, + TimeFrom: from, + ResourceID: key.ID, + ResourceName: key.Name, + ResourceType: key.Metric, + Unit: unit, + } + + if e := m.db.AddRecord(report); e != nil { + + err := "Acc: " + account + "-" + report.ResourceID + ". Error: " + e.Error() + queue <- err + + l.Trace.Printf("[TriggerManager] There was a problem adding the record in the system. Error: %v.\n", e) + + } else { + + l.Trace.Printf("[TriggerManager] Compacted record for account [ %v ] added to the system.\n", account) + + } + + } + + } + + r := models.UReport{ + AccountID: account, + TimeFrom: from, + TimeTo: to, + } + + if e := m.db.AddReport(r); e != nil { + + err := "Acc(r): " + account + ". Error: " + e.Error() + queue <- err + + l.Trace.Printf("[TriggerManager] There was a problem adding the Report in the system. Error: %v.\n", e) + + } else { + + udrCount++ + + l.Trace.Printf("[TriggerManager] Compacted report for account [ %v ] added to the system.\n", account) + + } + + }(accounts[i]) + + } + + }() + + // EE import and compactation + client := m.getClient(params.HTTPRequest) + + fu := ((time.Time)(from)).Unix() + tu := ((time.Time)(to)).Unix() + + eeParams := eventsUsage.NewGetSystemUsageParams().WithFrom(&fu).WithTo(&tu) + + r, e := client.UsageManagement.GetSystemUsage(ctx, eeParams) + + if e != nil { + + err := "EE(g)-Error: " + e.Error() + queue <- err + + l.Warning.Printf("[TriggerManager] There was a problem while importing data from EventsEngine. Error: %v", e) + + } else { + + for i := range r.Payload { + + swg.Add() + go func(ac *eeModels.Usage) { + + defer swg.Done() + + acc := *ac + + accum := make(map[CompactionKey]datamodels.JSONdb) + metas := make(map[CompactionKey]datamodels.JSONdb) + + // In the first part we calculate the usage by metadata + // And create a map of metadatas/matching keys + for id := range acc.Usage { + + key := CompactionKey{ + Account: acc.AccountID, + ID: acc.Usage[id].ResourceID, + Name: acc.Usage[id].ResourceName, + Metadata: fmt.Sprintf("%v", acc.Usage[id].MetaData), + Metric: acc.Usage[id].ResourceType, + Unit: acc.Usage[id].Unit, + } + + accum[key] = make(datamodels.JSONdb) + metas[key] = acc.Usage[id].MetaData + + for i := range acc.Usage[id].UsageBreakup { + + if _, exists := accum[key][i]; !exists { + + accum[key][i] = int64(0) + + } + + addition, _ := acc.Usage[id].UsageBreakup[i].(json.Number).Int64() + + accum[key][i] = accum[key][i].(int64) + addition + + } + + } + + // In the second part we add the compacted records in the system + for key := range accum { + + report := models.UDRRecord{ + AccountID: key.Account, + UsageBreakup: accum[key], + Metadata: metas[key], + TimeTo: to, + TimeFrom: from, + ResourceID: key.ID, + ResourceName: key.Name, + ResourceType: key.Metric, + Unit: key.Unit, + } + + if e := m.db.AddRecord(report); e != nil { + + err := "Acc: " + report.AccountID + "-" + report.ResourceID + ". Error: " + e.Error() + queue <- err + + l.Trace.Printf("[TriggerManager] There was a problem adding the record in the system. Error: %v.\n", e) + + } else { + + l.Trace.Printf("[TriggerManager] Compacted record for account [ %v ] added to the system.\n", report.AccountID) + + } + + } + + r := models.UReport{ + AccountID: acc.AccountID, + TimeFrom: from, + TimeTo: to, + } + + if e := m.db.AddReport(r); e != nil { + + err := "Acc(r): " + r.AccountID + ". Error: " + e.Error() + queue <- err + + l.Trace.Printf("[TriggerManager] There was a problem adding the Report in the system. Error: %v.\n", e) + + } else { + + udrCount++ + + l.Trace.Printf("[TriggerManager] Compacted report for account [ %v ] added to the system.\n", r.AccountID) + + } + + }(r.Payload[i]) + + } + + } + + swg.Wait() + + // Kafka report + accs := m.db.GetUDRAccounts() + + for _, acc := range accs { + + usages, e := m.db.GetUsage(acc, "", from, to) + + if e == nil { + + l.Trace.Printf("[TriggerManager] There's [ %v ] compacted usages associated with the account [ %v ].\n", len(usages), acc) + + for _, usage := range usages { + + m.pipe <- *usage + + } + + } else { + + err := "Usage(g)-Acc: " + acc + ". Error: " + e.Error() + queue <- err + + l.Warning.Printf("[TriggerManager] There was a problem while retrieving the compacted usages to be sent through Kafka. Error: %v", e) + + } + + } + + close(queue) + + m.db.Metrics["time"].With(prometheus.Labels{"type": "UDRs generation time"}).Set(float64(time.Now().UnixNano()-now.UnixNano()) / float64(time.Millisecond)) + + m.db.Metrics["count"].With(prometheus.Labels{"type": "UDRs generated"}).Set(float64(udrCount)) + + m.db.Metrics["count"].With(prometheus.Labels{"type": "Errors during UDR generation"}).Set(float64(len(accumErr))) + + if len(accumErr) > 0 { + + s := "This are the accumulative errors: " + strings.Join(accumErr, ",\n") + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/trigger/compact"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecCompactationInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/trigger/compact"}).Inc() + + m.monit.APIHitDone("trigger", callTime) + + return trigger_management.NewExecCompactationOK() + +} diff --git a/services/udr/server/usageManager/usageManager.go b/services/udr/server/usageManager/usageManager.go new file mode 100644 index 0000000..9f009bd --- /dev/null +++ b/services/udr/server/usageManager/usageManager.go @@ -0,0 +1,169 @@ +package usageManager + +import ( + "context" + "time" + + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/prometheus/client_golang/prometheus" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/models" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/restapi/operations/usage_management" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/dbManager" + "github.com/Cyclops-Labs/cyclops-4-hpc.git/services/udr/server/statusManager" + l "gitlab.com/cyclops-utilities/logging" +) + +// UsageManager is the struct defined to group and contain all the methods +// that interact with the usage endpoint. +// Parameters: +// - db: a DbParameter reference to be able to use the DBManager methods. +// - monit: a StatusManager reference to be able to use the status subsystem methods. +type UsageManager struct { + db *dbManager.DbParameter + monit *statusManager.StatusManager +} + +// New is the function to create the struct UsageManager that grant +// access to the methods to interact with the usage endpoint. +// Parameters: +// - db: a reference to the DbParameter to be able to interact with the db methods. +// - monit: a reference to the StatusManager to be able to interact with the +// status subsystem. +// Returns: +// - UsageManager: struct to interact with the usage endpoint functionalities. +func New(db *dbManager.DbParameter, monit *statusManager.StatusManager) *UsageManager { + + l.Trace.Printf("[UsageManager] Generating new ResellerManager.\n") + + monit.InitEndpoint("usage") + + return &UsageManager{ + db: db, + monit: monit, + } + +} + +// GetSystemUsage (Swagger func) is the function behind the (GET) endpoint +// /usage +// Its job is to retrieve the usage report given a certain time-window and with +// the posibility of filtering by metric. +func (m *UsageManager) GetSystemUsage(ctx context.Context, params usage_management.GetSystemUsageParams) middleware.Responder { + + l.Trace.Printf("[UsageManager] GetSystemUsage endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("usage", callTime) + + var from, to strfmt.DateTime + + list := "" + metric := "" + + if params.From != nil { + + from = *params.From + + } + + if params.Idlist != nil { + + list = *params.Idlist + + } + + if params.Metric != nil { + + metric = *params.Metric + + } + + if params.To != nil { + + to = *params.To + + } + + usage, e := m.db.GetUsages(list, metric, from, to) + + if e != nil { + + s := "There was an error retrieving the Usage from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/usage"}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetSystemUsageInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage"}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetSystemUsageOK().WithPayload(usage) + +} + +// GetUsage (Swagger func) is the function behind the (GET) endpoint +// /usage/{id} +// Its job is to retrieve the usage report of the given account during the +// defined time-window, with the posibility of filtering by metric. +func (m *UsageManager) GetUsage(ctx context.Context, params usage_management.GetUsageParams) middleware.Responder { + + l.Trace.Printf("[UsageManager] GetUsage endpoint invoked.\n") + + callTime := time.Now() + m.monit.APIHit("usage", callTime) + + var from, to strfmt.DateTime + + metric := "" + + if params.From != nil { + + from = *params.From + + } + + if params.Metric != nil { + + metric = *params.Metric + + } + + if params.To != nil { + + to = *params.To + + } + + usage, e := m.db.GetUsage(params.ID, metric, from, to) + + if e != nil { + + s := "There was an error retrieving the Usage from the system: " + e.Error() + errorReturn := models.ErrorResponse{ + ErrorString: &s, + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "500", "method": "GET", "route": "/usage/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageInternalServerError().WithPayload(&errorReturn) + + } + + m.db.Metrics["api"].With(prometheus.Labels{"code": "200", "method": "GET", "route": "/usage/" + params.ID}).Inc() + + m.monit.APIHitDone("usage", callTime) + + return usage_management.NewGetUsageOK().WithPayload(usage) + +} diff --git a/services/udr/swagger.yaml b/services/udr/swagger.yaml new file mode 100644 index 0000000..7fa349c --- /dev/null +++ b/services/udr/swagger.yaml @@ -0,0 +1,386 @@ +--- +swagger: "2.0" +host: "localhost:8000" +basePath: "/api/v1.0" +info: + description: An API which supports creation, deletion, listing etc of UDR + version: "1.0.0" + title: UDR Management API + contact: + email: diego@cyclops-labs.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' + +tags: + - name: statusManagement + description: Actions relating to the reporting of the state of the service + - name: triggerManagement + description: Actions relating to the periodics actions to be triggered in the system + - name: metricsManagement + description: Actions relating to the metrics used and controlled by the system + - name: usageManagement + description: Actions relating to the usage reporting of the accounts of the system + +securityDefinitions: + APIKeyHeader: + type: apiKey + in: header + name: X-API-KEY + APIKeyParam: + type: apiKey + in: query + name: api_key + Keycloak: + type: oauth2 + flow: accessCode + authorizationUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/auth' + tokenUrl: 'http://localhost:8080/auth/realms/Dev/protocol/openid-connect/token' + scopes: + admin: Admin scope + user: User scope + +schemes: + - http + - https + +security: + - Keycloak: [user,admin] + - APIKeyHeader: [] + - APIKeyParam: [] + +paths: + /status: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: showStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + /status/{id}: + get: + tags: + - statusManagement + produces: + - application/json + summary: Basic status of the system + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getStatus + responses: + '200': + description: Status information of the system + schema: + $ref: "#/definitions/Status" + '404': + description: The endpoint provided doesn't exist + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + type: string + enum: + - kafka-receiver + - kafka-sender + - status + - trigger + - metrics + - usage + required: true + description: Id of the endpoint to be checked + + /trigger/compact: + get: + tags: + - triggerManagement + produces: + - application/json + summary: Compactation task trigger + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: execCompactation + responses: + '200': + description: Compactation task executed successfully. + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: from + in: query + description: Datetime from which to get the usage report + type: string + format: datetime + - name: to + in: query + description: Datetime until which to get the usage report + type: string + format: datetime + - name: fast_mode + in: query + description: Switch for using 15m boundaries instead of 8h + type: boolean + + /metrics: + get: + tags: + - metricsManagement + produces: + - application/json + summary: List of all metric types processed by the service + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getMetrics + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/Metric" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + + /usage: + get: + tags: + - usageManagement + produces: + - application/json + summary: Detailed report covering all accounts within the specified time window + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getSystemUsage + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/UReport" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: from + in: query + description: Datetime from which to get the usage report + type: string + format: datetime + - name: to + in: query + description: Datetime until which to get the usage report + type: string + format: datetime + - name: metric + in: query + description: Metric(s) to get the usage report + type: string + - name: idlist + in: query + description: List of ids to be queried + type: string + /usage/{id}: + get: + tags: + - usageManagement + produces: + - application/json + summary: Detailed report covering of the account associated with the id within the specified time window + security: + - Keycloak: [user] + - APIKeyHeader: [] + - APIKeyParam: [] + operationId: getUsage + responses: + '200': + description: Description of a successfully operation + schema: + type: array + items: + $ref: "#/definitions/UReport" + '500': + description: Something unexpected happend, error raised + schema: + $ref: "#/definitions/ErrorResponse" + parameters: + - name: id + in: path + description: Id of the account to be checked + required: true + type: string + - name: from + in: query + description: Datetime from which to get the usage report + type: string + format: datetime + - name: to + in: query + description: Datetime until which to get the usage report + type: string + format: datetime + - name: metric + in: query + description: Metric(s) to get the usage report + type: string + +definitions: + ErrorResponse: + type: object + required: + - errorString + properties: + errorString: + type: string + Metadata: + type: object + x-go-type: + import: + package: "gitlab.com/cyclops-enterprise/datamodels" + type: JSONdb + Status: + type: object + required: + - SystemState + properties: + AverageResponseTime: + type: number + format: double + DBState: + type: string + LastRequest: + type: string + RequestsBoT: + type: integer + RequestsLastHour: + type: integer + RequestsToday: + type: integer + SystemState: + type: string + + Metric: + type: object + properties: + Metric: + type: string + x-go-custom-tag: gorm:"primary_key" + + UReport: + type: object + properties: + AccountId: + type: string + x-go-custom-tag: gorm:"index" + TimeFrom: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + TimeTo: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + Usage: + type: array + x-go-custom-tag: gorm:"-" + items: + $ref: "#/definitions/UDRReport" + + UDRRecord: + type: object + properties: + AccountId: + type: string + x-go-custom-tag: gorm:"index" + Metadata: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + ResourceId: + type: string + ResourceName: + type: string + ResourceType: + type: string + TimeFrom: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + TimeTo: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + Unit: + type: string + UsageBreakup: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + + UDRReport: + type: object + properties: + Metadata: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + ResourceId: + type: string + ResourceName: + type: string + ResourceType: + type: string + Unit: + type: string + UsageBreakup: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + + Usage: + type: object + properties: + Account: + type: string + x-go-custom-tag: gorm:"index" + Metadata: + x-go-custom-tag: gorm:"type:jsonb" + $ref: '#/definitions/Metadata' + ResourceID: + type: string + ResourceName: + type: string + ResourceType: + type: string + Time: + type: integer + Timedate: + type: string + format: datetime + x-go-custom-tag: gorm:"index;type:timestamptz" + Unit: + type: string + Usage: + type: number + x-go-custom-tag: gorm:"type:numeric(23,13);default:0.0" + format: double + default: 0.0