diff --git a/configuration/configuration.go b/configuration/configuration.go index fbd87358..53cd5a83 100644 --- a/configuration/configuration.go +++ b/configuration/configuration.go @@ -129,6 +129,8 @@ type NotifyConfiguration struct { type ServiceDiscovery struct { consulMu sync.Mutex Consuls []*models.Consul `yaml:"consuls" group:"service_discovery" save:"true"` + nomadMu sync.Mutex + Nomads []*models.Nomad `yaml:"nomads" group:"service_discovery" save:"true"` awsMu sync.Mutex AWSRegions []*models.AwsRegion `yaml:"aws-regions" group:"service_discovery" save:"true"` } @@ -273,11 +275,15 @@ func (c *Configuration) Save() error { cfg := c.storage.Get() cfg.ServiceDiscovery.Consuls = nil } + if len(c.ServiceDiscovery.Nomads) == 0 { + cfg := c.storage.Get() + cfg.ServiceDiscovery.Nomads = nil + } if len(c.ServiceDiscovery.AWSRegions) == 0 { cfg := c.storage.Get() cfg.ServiceDiscovery.AWSRegions = nil } - if cfg.ServiceDiscovery.Consuls == nil && cfg.ServiceDiscovery.AWSRegions == nil { + if cfg.ServiceDiscovery.Consuls == nil && cfg.ServiceDiscovery.AWSRegions == nil && cfg.ServiceDiscovery.Nomads == nil { cfg := c.storage.Get() cfg.ServiceDiscovery = nil } @@ -317,6 +323,13 @@ func (c *Configuration) SaveConsuls(consuls []*models.Consul) error { return c.Save() } +func (c *Configuration) SaveNomads(nomads []*models.Nomad) error { + c.ServiceDiscovery.nomadMu.Lock() + c.ServiceDiscovery.Nomads = nomads + c.ServiceDiscovery.nomadMu.Unlock() + return c.Save() +} + func (c *Configuration) SaveAWS(aws []*models.AwsRegion) error { c.ServiceDiscovery.awsMu.Lock() defer c.ServiceDiscovery.awsMu.Unlock() diff --git a/configuration/configuration_storage.go b/configuration/configuration_storage.go index 6e552e06..a49efb57 100644 --- a/configuration/configuration_storage.go +++ b/configuration/configuration_storage.go @@ -1,4 +1,3 @@ -// Code generated by go generate; DO NOT EDIT. // Copyright 2021 HAProxy Technologies // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -85,7 +84,7 @@ type configTypeReload struct { ReloadDelay *int `yaml:"reload_delay,omitempty" hcl:"reload_delay,omitempty"` ReloadCmd *string `yaml:"reload_cmd,omitempty" hcl:"reload_cmd,omitempty"` RestartCmd *string `yaml:"restart_cmd,omitempty" hcl:"restart_cmd,omitempty"` - StatusCmd *string `yaml:"status_cmd,omitempty" hcl:"status_cmd,omitempty"` + StatusCmd *string `yaml:"status_cmd,omitempty" hcl:"status_cmd,omitempty"` ReloadRetention *int `yaml:"reload_retention,omitempty" hcl:"reload_retention,omitempty"` ValidateCmd *string `yaml:"validate_cmd,omitempty" hcl:"validate_cmd,omitempty"` } @@ -134,6 +133,7 @@ type configTypeAdvertised struct { type configTypeServiceDiscovery struct { Consuls *[]*models.Consul `yaml:"consuls,omitempty" hcl:"consuls,omitempty"` + Nomads *[]*models.Nomad `yaml:"nomads,omitempty" hcl:"nomads,omitempty"` AWSRegions *[]*models.AwsRegion `yaml:"aws_regions,omitempty" hcl:"aws_regions,omitempty"` } @@ -344,6 +344,9 @@ func copyToConfiguration(cfg *Configuration) { if cfgStorage.ServiceDiscovery != nil && cfgStorage.ServiceDiscovery.Consuls != nil && !misc.HasOSArg("", "", "") { cfg.ServiceDiscovery.Consuls = *cfgStorage.ServiceDiscovery.Consuls } + if cfgStorage.ServiceDiscovery != nil && cfgStorage.ServiceDiscovery.Nomads != nil && !misc.HasOSArg("", "", "") { + cfg.ServiceDiscovery.Nomads = *cfgStorage.ServiceDiscovery.Nomads + } if cfgStorage.ServiceDiscovery != nil && cfgStorage.ServiceDiscovery.AWSRegions != nil && !misc.HasOSArg("", "", "") { cfg.ServiceDiscovery.AWSRegions = *cfgStorage.ServiceDiscovery.AWSRegions } @@ -522,6 +525,11 @@ func copyConfigurationToStorage(cfg *Configuration) { } cfgStorage.ServiceDiscovery.AWSRegions = &cfg.ServiceDiscovery.AWSRegions + if cfgStorage.ServiceDiscovery == nil { + cfgStorage.ServiceDiscovery = &configTypeServiceDiscovery{} + } + cfgStorage.ServiceDiscovery.Nomads = &cfg.ServiceDiscovery.Nomads + if cfgStorage.LogTargets == nil { cfgStorage.LogTargets = &dpapilog.Targets{} } diff --git a/configuration/examples/example-dataplaneapi.yaml b/configuration/examples/example-dataplaneapi.yaml index 252d2cc0..f23402c9 100644 --- a/configuration/examples/example-dataplaneapi.yaml +++ b/configuration/examples/example-dataplaneapi.yaml @@ -3,9 +3,9 @@ dataplaneapi: host: 0.0.0.0 port: 8080 user: - - name: admin - insecure: true - password: adminpwd + - name: admin + insecure: true + password: adminpwd resources: maps_dir: /etc/haproxy/maps ssl_certs_dir: /etc/haproxy/ssl diff --git a/configuration/examples/example-full.hcl b/configuration/examples/example-full.hcl index 47eb0109..b3e887f3 100644 --- a/configuration/examples/example-full.hcl +++ b/configuration/examples/example-full.hcl @@ -1,35 +1,35 @@ config_version = 2 -name = "famous_condor" -mode = "single" -status = "null" +name = "famous_condor" +mode = "single" +status = "null" dataplaneapi { - scheme = ["http"] - cleanup_timeout = "10s" + scheme = ["http"] + cleanup_timeout = "10s" graceful_timeout = "15s" - max_header_size = "1MiB" - socket_path = "/var/run/data-plane.sock" - host = "localhost" - port = 80 - listen_limit = 1024 - keep_alive = "3m" - read_timeout = "30s" - write_timeout = "60s" + max_header_size = "1MiB" + socket_path = "/var/run/data-plane.sock" + host = "localhost" + port = 80 + listen_limit = 1024 + keep_alive = "3m" + read_timeout = "30s" + write_timeout = "60s" show_system_info = false - disable_inotify = false - pid_file = "/tmp/dataplane.pid" - uid = 1000 - gid = 1000 + disable_inotify = false + pid_file = "/tmp/dataplane.pid" + uid = 1000 + gid = 1000 tls { - tls_host = "null" - tls_port = 6443 - tls_certificate = "null" - tls_key = "null" - tls_ca = "null" - tls_listen_limit = 10 - tls_keep_alive = "1m" - tls_read_timeout = "10s" + tls_host = "null" + tls_port = 6443 + tls_certificate = "null" + tls_key = "null" + tls_ca = "null" + tls_listen_limit = 10 + tls_keep_alive = "1m" + tls_read_timeout = "10s" tls_write_timeout = "10s" } @@ -39,88 +39,88 @@ dataplaneapi { } userlist { - userlist = "controller" + userlist = "controller" userlist_file = "null" } transaction { - transaction_dir = "/tmp/haproxy" - backups_number = 0 - backups_dir = "/tmp/backups" + transaction_dir = "/tmp/haproxy" + backups_number = 0 + backups_dir = "/tmp/backups" max_open_transactions = 20 } resources { - maps_dir = "/etc/haproxy/maps" - ssl_certs_dir = "/etc/haproxy/ssl" - update_map_files = false + maps_dir = "/etc/haproxy/maps" + ssl_certs_dir = "/etc/haproxy/ssl" + update_map_files = false update_map_files_period = 10 - spoe_dir = "/etc/haproxy/spoe" - spoe_transaction_dir = "/tmp/spoe-haproxy" + spoe_dir = "/etc/haproxy/spoe" + spoe_transaction_dir = "/tmp/spoe-haproxy" } advertised { api_address = "10.2.3.4" - api_port = 80 + api_port = 80 } } haproxy { - config_file = "/etc/haproxy/haproxy.cfg" - haproxy_bin = "haproxy" - master_runtime = "null" - fid = "null" + config_file = "/etc/haproxy/haproxy.cfg" + haproxy_bin = "haproxy" + master_runtime = "null" + fid = "null" master_worker_mode = false reload { - reload_delay = 5 - reload_cmd = "systemctl reload haproxy" - restart_cmd = "systemctl restart haproxy" - status_cmd = "systemctl status haproxy" + reload_delay = 5 + reload_cmd = "systemctl reload haproxy" + restart_cmd = "systemctl restart haproxy" + status_cmd = "systemctl status haproxy" reload_retention = 1 - validate_cmd = "null" + validate_cmd = "null" } } cluster { - cluster_tls_dir = "null" - id = "null" - bootstrap_key = "null" + cluster_tls_dir = "null" + id = "null" + bootstrap_key = "null" active_bootstrap_key = "null" - token = "null" - url = "null" - port = 80 - api_base_path = "null" - api_nodes_path = "null" - api_register_path = "null" - storage_dir = "null" - cert_path = "null" - cert_fetched = false - name = "null" - description = "null" + token = "null" + url = "null" + port = 80 + api_base_path = "null" + api_nodes_path = "null" + api_register_path = "null" + storage_dir = "null" + cert_path = "null" + cert_fetched = false + name = "null" + description = "null" } service_discovery { - consuls = [] + consuls = [] aws_regions = [] } log_targets = [ { - log_to = "stdout" - log_level = "debug" - log_format = "json" + log_to = "stdout" + log_level = "debug" + log_format = "json" log_types = [ "access", "app", ] }, { - log_to = "file" - log_file = "/var/log/dataplanepi.log" - log_level = "info" - log_format = "text" - log_types = ["app"] + log_to = "file" + log_file = "/var/log/dataplanepi.log" + log_level = "info" + log_format = "text" + log_types = ["app"] }, { log_to = "syslog" @@ -136,17 +136,17 @@ log_targets = [ # Deprecated: use log_targets instead log { - log_to = "stdout" - log_file = "/var/log/dataplaneapi/dataplaneapi.log" - log_level = "warning" - log_format = "text" + log_to = "stdout" + log_file = "/var/log/dataplaneapi/dataplaneapi.log" + log_level = "warning" + log_format = "text" apache_common_log_format = "%h" syslog { - syslog_address = "null" + syslog_address = "null" syslog_protocol = "tcp" - syslog_tag = "dataplaneapi" - syslog_level = "debug" + syslog_tag = "dataplaneapi" + syslog_level = "debug" syslog_facility = "local0" } } diff --git a/configure_data_plane.go b/configure_data_plane.go index 77665ffc..a262c291 100644 --- a/configure_data_plane.go +++ b/configure_data_plane.go @@ -648,12 +648,21 @@ func configureAPI(api *operations.DataPlaneAPI) http.Handler { ReloadAgent: ra, Context: ctx, }) + // Consul Handlers. api.ServiceDiscoveryCreateConsulHandler = &handlers.CreateConsulHandlerImpl{Discovery: discovery, PersistCallback: cfg.SaveConsuls} api.ServiceDiscoveryDeleteConsulHandler = &handlers.DeleteConsulHandlerImpl{Discovery: discovery, PersistCallback: cfg.SaveConsuls} api.ServiceDiscoveryGetConsulHandler = &handlers.GetConsulHandlerImpl{Discovery: discovery} api.ServiceDiscoveryGetConsulsHandler = &handlers.GetConsulsHandlerImpl{Discovery: discovery} api.ServiceDiscoveryReplaceConsulHandler = &handlers.ReplaceConsulHandlerImpl{Discovery: discovery, PersistCallback: cfg.SaveConsuls} + // Nomad Handlers. + api.ServiceDiscoveryCreateNomadHandler = &handlers.CreateNomadHandlerImpl{Discovery: discovery, PersistCallback: cfg.SaveNomads} + api.ServiceDiscoveryDeleteNomadHandler = &handlers.DeleteNomadHandlerImpl{Discovery: discovery, PersistCallback: cfg.SaveNomads} + api.ServiceDiscoveryGetNomadHandler = &handlers.GetNomadHandlerImpl{Discovery: discovery} + api.ServiceDiscoveryGetNomadsHandler = &handlers.GetNomadsHandlerImpl{Discovery: discovery} + api.ServiceDiscoveryReplaceNomadHandler = &handlers.ReplaceNomadHandlerImpl{Discovery: discovery, PersistCallback: cfg.SaveNomads} + + // AWS Handlers. api.ServiceDiscoveryCreateAWSRegionHandler = &handlers.CreateAWSHandlerImpl{Discovery: discovery, PersistCallback: cfg.SaveAWS} api.ServiceDiscoveryGetAWSRegionHandler = &handlers.GetAWSRegionHandlerImpl{Discovery: discovery} api.ServiceDiscoveryGetAWSRegionsHandler = &handlers.GetAWSRegionsHandlerImpl{Discovery: discovery} @@ -675,6 +684,21 @@ func configureAPI(api *operations.DataPlaneAPI) http.Handler { } _ = cfg.SaveConsuls(cfg.ServiceDiscovery.Consuls) + // Create stored nomad instances. + for _, data := range cfg.ServiceDiscovery.Nomads { + var errSD error + if data.ID == nil || len(*data.ID) == 0 { + data.ID = service_discovery.NewServiceDiscoveryUUID() + } + if errSD = service_discovery.ValidateNomadData(data, true); errSD != nil { + log.Fatalf("Error validating Nomad instance: " + errSD.Error()) + } + if errSD = discovery.AddNode("nomad", *data.ID, data); errSD != nil { + log.Warning("Error creating nomad instance: " + errSD.Error()) + } + } + _ = cfg.SaveNomads(cfg.ServiceDiscovery.Nomads) + // create stored AWS instances for _, data := range cfg.ServiceDiscovery.AWSRegions { var errSD error diff --git a/discovery/NOMAD.md b/discovery/NOMAD.md new file mode 100644 index 00000000..1cf4dc51 --- /dev/null +++ b/discovery/NOMAD.md @@ -0,0 +1,184 @@ +# Nomad service discovery + +Dataplane enables connecting to an existing Nomad cluster and map Service Registrations into HAProxy backends. + +# Connecting to Nomad + +To connect Dataplane to an existing Nomad cluster, an HTTP request to `service_discovery/nomad` needs to be sent: + +```json +curl -XPOST "http://localhost:5555/v2/service_discovery/nomad" -H 'content-type: application/json' -d @/path/to/payload.json +{ + "secret_id": "****************", + "enabled": true, + "name": "my-nomad-service", + "description": "Nomad test system", + "address": "http://127.0.0.1", + "port" : 4646, + "namespace": "default", + "retry_timeout": 60 +} +// Response: +{ + "address": "http://127.0.0.1", + "allowlist": null, + "denylist": null, + "description": "Nomad test system", + "enabled": true, + "id": "931e5ed0-9ac1-434c-b026-4d02f5c2fadb", + "name": "my-nomad-service", + "namespace": "*", + "port": 4646, + "retry_timeout": 60, + "secret_id": "****************", + "server_slots_base": 10, + "server_slots_growth_increment": 10, + "server_slots_growth_type": "linear" +} +``` + +**NOTE** + +- If there's no ACL on Nomad cluster then `secret_id` can be left empty. +- To discover services across all Nomad namespaces, `*` (wildcard) operator can be used. + +Alternatively, the configuration can be set in a file either in `.hcl` or `.yaml` form: + +```hcl +service_discovery { + nomads = [ + { + Address = "http://127.0.0.1" + Description = "Nomad test system" + Enabled = true + ID = "b40eb63b-2fb2-4996-b870-20f50ca173de" + Name = "my-nomad-service" + Namespace = "default" + Port = 4646 + RetryTimeout = 15 + SecretID = "" + ServerSlotsBase = 10 + ServerSlotsGrowthIncrement = 10 + ServerSlotsGrowthType = "linear" + }, + ] +} +``` + +```yaml +service_discovery: + nomads: + - address: http://127.0.0.1 + allowlist: [] + denylist: [] + description: Nomad test system + enabled: true + id: b40eb63b-2fb2-4996-b870-20f50ca173de + name: my-nomad-service + namespace: '*' + port: 4646 + retrytimeout: 15 + secretid: "" + serverslotsbase: 10 + serverslotsgrowthincrement: 10 + serverslotsgrowthtype: linear +``` + +## Filtering Services + +By default, dataplane will attempt to fetch all services for a given namespace. Using the `allowlist` and `denylist` fields a list of services to be tracked or ignored respectively can be provided. The `allowlist` option has precedence. Both of these filtering options can be used simultaneously. + +The service name is of the format: `-`. + +To filter for `good-svc` registered inside `default` namespace the following example can be used: + +```hcl +service_discovery { + nomads = [ + { + ... + Allowlist = ["default-good-svc"] + Denylist = ["default-bad-svc"] + ... + }, + ] +} +``` + +## Discovering all services + +Namespace filtering can be done by providing the `namespace` option. Only one namespace can be specified and only services from that +namespaces will be tracked. Specifying `*` would return all services across all the authorized namespaces. + +## Authorization + +If ACL is enabled on Nomad cluster, then a valid ACL token should be configured with the `secret_id` field in Nomad service discovery configuration. A valid ACL policy should also be attached to this ACL token. + +An example of an ACL policy which allows to discover services across all namespaces: + +```hcl +namespace "*" { + policy = "read-job" +} +``` + +## Updating + +After a nomad service discovery is connected to dataplane it's data will be polled every `retry_timeout` amount of seconds. Nomad Services HTTP API +is used to check if there have been changes for each individual service and if there were the server list for that +service gets updated. The changes to all services in a single update cycle are done in a single transaction. If the nomad instance +gets updated and the `enabled` parameter gets set to `false` data for that instance will not be pulled anymore but the existing configuration +for that service persists in its current state. + +## Server slot scaling + +The amount of server lines in a backend can be controlled using the `server_slots_base`, `server_slots_growth_type` and `server_slots_growth_increment` parameters. The `server_slots_base` option indicates how many servers are created on backend creation. Once the base slots used up the servers +expand based on the `server_slots_growth_type`: +- `linear` : on each expansion the number of servers increases by the amount specified in `server_slots_growth_increment` +- `exponential` : the number of servers doubles on each server count increase +In case nodes get removed from the service the number of servers in the backend will decrease based on the specified growth type. + +# Examples + +## Creating a discovery on a selected Nomad namespace for all services + +The following example shows how to fetch all services inside `orange` namespace and reconcilie every 15s. + +```hcl +service_discovery { + nomads = [ + { + Address = "http://127.0.0.1" + Description = "Nomad Service discovery for orange namespace" + Enabled = true + ID = "b40eb63b-2fb2-4996-b870-20f50ca173de" + Name = "example-nomad-svc" + Namespace = "orange" + Port = 4646 + RetryTimeout = 15 + }, + ] +} +``` + +The backend in the haproxy configuration associated with the nomad service `web-fruits` in `orange` namespace will have the following format: + +``` +backend nomad-backend-orange-web-fruits + server SRV_fDxC4 192.168.29.76:31513 check weight 128 + server SRV_m12Um 192.168.29.76:26146 check weight 128 + server SRV_Yi8sO 192.168.29.76:31528 check weight 128 + server SRV_nQOhc 192.168.29.76:27266 check weight 128 + server SRV_II8XR 127.0.0.1:80 disabled weight 128 + server SRV_YV0co 127.0.0.1:80 disabled weight 128 + server SRV_A8zUR 127.0.0.1:80 disabled weight 128 + server SRV_khA3j 127.0.0.1:80 disabled weight 128 + server SRV_w1B3d 127.0.0.1:80 disabled weight 128 + server SRV_ZxeUk 127.0.0.1:80 disabled weight 128 +``` + +The backend name will always have the following format: `nomad-backend--`. + +Each node associated with the services is represented by a server line with the following format: `server SRV_ : weight 128` + +In addition some additional disabled server lines will be added for future nodes to be used. diff --git a/discovery/README.md b/discovery/README.md index 5c29018d..68d2aca1 100644 --- a/discovery/README.md +++ b/discovery/README.md @@ -7,3 +7,7 @@ Check the AWS Service Discovery [README](./AWS.md). ## CONSUL Check the CONSUL Service Discovery [README](./CONSUL.md). + +## Nomad + +Check the Nomad Service Discovery [README](./Nomad.md). diff --git a/discovery/nomad_service_discovery.go b/discovery/nomad_service_discovery.go new file mode 100644 index 00000000..466ea43c --- /dev/null +++ b/discovery/nomad_service_discovery.go @@ -0,0 +1,123 @@ +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package discovery + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/haproxytech/client-native/v4/configuration" + "github.com/haproxytech/client-native/v4/models" + "github.com/haproxytech/dataplaneapi/haproxy" +) + +type nomadServiceDiscovery struct { + nomadServices Store + client configuration.Configuration + reloadAgent haproxy.IReloadAgent + context context.Context +} + +// NewNomadDiscoveryService creates a new ServiceDiscovery that connects to Nomad. +func NewNomadDiscoveryService(params ServiceDiscoveriesParams) ServiceDiscovery { + return &nomadServiceDiscovery{ + nomadServices: NewInstanceStore(), + client: params.Client, + reloadAgent: params.ReloadAgent, + context: params.Context, + } +} + +func (n *nomadServiceDiscovery) AddNode(id string, params ServiceDiscoveryParams) (err error) { + nParams, ok := params.(*models.Nomad) + if !ok { + return errors.New("expected models.Nomad") + } + + var timeout time.Duration + timeout, err = time.ParseDuration(fmt.Sprintf("%ds", *nParams.RetryTimeout)) + if err != nil { + return err + } + + logFields := map[string]interface{}{"ServiceDiscovery": "Nomad", "ID": *nParams.ID} + + instance := &nomadInstance{ + params: nParams, + ctx: n.context, + timeout: timeout, + discoveryConfig: NewServiceDiscoveryInstance(n.client, n.reloadAgent, discoveryInstanceParams{ + Allowlist: nParams.Allowlist, + Denylist: nParams.Denylist, + LogFields: logFields, + ServerSlotsBase: int(*nParams.ServerSlotsBase), + SlotsGrowthType: *nParams.ServerSlotsGrowthType, + SlotsIncrement: int(nParams.ServerSlotsGrowthIncrement), + }), + prevIndexes: make(map[string]uint64), + logFields: logFields, + } + + if err = n.nomadServices.Create(id, instance); err != nil { + return + } + + instance.prevEnabled = *nParams.Enabled + + if *nParams.Enabled { + return instance.start() + } + return nil +} + +func (n *nomadServiceDiscovery) GetNode(id string) (p ServiceDiscoveryParams, err error) { + var i interface{} + if i, err = n.nomadServices.Read(id); err != nil { + return + } + p = i.(*nomadInstance).params + return +} + +func (n *nomadServiceDiscovery) GetNodes() (ServiceDiscoveryParams, error) { + var nomads models.Nomads + for _, ni := range n.nomadServices.List() { + nomads = append(nomads, ni.(*nomadInstance).params) + } + return nomads, nil +} + +func (n *nomadServiceDiscovery) RemoveNode(id string) error { + return n.nomadServices.Delete(id) +} + +func (n *nomadServiceDiscovery) UpdateNode(id string, params ServiceDiscoveryParams) (err error) { + nParams, ok := params.(*models.Nomad) + if !ok { + return errors.New("expected models.Nomads") + } + return n.nomadServices.Update(id, func(item interface{}) error { + ni := item.(*nomadInstance) + ni.params = nParams + if err = ni.updateTimeout(int(*nParams.RetryTimeout)); err != nil { + ni.stop() + return errors.New("invalid retry_timeout") + } + return ni.handleStateChange() + }) +} diff --git a/discovery/nomad_service_discovery_instance.go b/discovery/nomad_service_discovery_instance.go new file mode 100644 index 00000000..0eb7ad73 --- /dev/null +++ b/discovery/nomad_service_discovery_instance.go @@ -0,0 +1,237 @@ +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package discovery + +import ( + "context" + "fmt" + "time" + + "github.com/haproxytech/client-native/v4/configuration" + "github.com/haproxytech/client-native/v4/models" + "github.com/haproxytech/dataplaneapi/log" + + "github.com/hashicorp/nomad/api" +) + +type nomadService struct { + name string + changed bool + params *models.Nomad + servers []configuration.ServiceServer +} + +func (n *nomadService) GetName() string { + return n.name +} + +func (n *nomadService) GetBackendName() string { + return fmt.Sprintf("nomad-backend-%s-%s", n.params.Name, n.GetName()) +} + +func (n *nomadService) Changed() bool { + return n.changed +} + +func (n *nomadService) GetServers() []configuration.ServiceServer { + return n.servers +} + +type nomadInstance struct { + params *models.Nomad + api *api.Client + discoveryConfig *ServiceDiscoveryInstance + prevIndexes map[string]uint64 + timeout time.Duration + prevEnabled bool + ctx context.Context + update chan struct{} + logFields map[string]interface{} +} + +func (n *nomadInstance) start() error { + n.logDebug("discovery job starting") + if err := n.setAPIClient(); err != nil { + return err + } + n.update = make(chan struct{}, 1) + go n.watch() + return nil +} + +func (n *nomadInstance) setAPIClient() error { + address := fmt.Sprintf("%s:%d", *n.params.Address, *n.params.Port) + nomadCfg := api.DefaultConfig() + nomadCfg.Address = address + nomadCfg.SecretID = n.params.SecretID + nc, err := api.NewClient(nomadCfg) + if err != nil { + return err + } + n.api = nc + return nil +} + +func (n *nomadInstance) watch() { + watchTimer := time.NewTimer(n.timeout) + defer watchTimer.Stop() + + for { + select { + case _, ok := <-n.update: + if !ok { + return + } + n.logDebug("discovery job update triggered") + if err := n.setAPIClient(); err != nil { + n.logErrorf("error while setting up the API client: %s", err.Error()) + n.stop() + continue + } + err := n.discoveryConfig.UpdateParams(discoveryInstanceParams{ + Allowlist: n.params.Allowlist, + Denylist: n.params.Denylist, + LogFields: n.logFields, + ServerSlotsBase: int(*n.params.ServerSlotsBase), + SlotsGrowthType: *n.params.ServerSlotsGrowthType, + SlotsIncrement: int(n.params.ServerSlotsGrowthIncrement), + }) + if err != nil { + n.stop() + n.logErrorf("error while updating the instance: %s", err.Error()) + } + case <-n.ctx.Done(): + n.stop() + case <-watchTimer.C: + n.logDebug("discovery job reconciliation started") + if err := n.updateServices(); err != nil { + n.logErrorf("error while updating service: %s", err.Error()) + } + n.logDebug("discovery job reconciliation completed") + watchTimer.Reset(n.timeout) + } + } +} + +func (n *nomadInstance) stop() { + n.logDebug("discovery job stopping") + n.api = nil + n.prevEnabled = false + close(n.update) +} + +func (n *nomadInstance) updateServices() error { + services := make([]ServiceInstance, 0) + + // Set query options. + query := &api.QueryOptions{} + if n.params.Namespace != "" { + query.Namespace = n.params.Namespace + } + + // Fetch list of services from Nomad API. + nServices, _, err := n.api.Services().List(query) + if err != nil { + return err + } + + newIndexes := make(map[string]uint64) + + for _, nSvc := range nServices { + for _, s := range nSvc.Services { + svcRegistrations, meta, err := n.api.Services().Get(s.ServiceName, (&api.QueryOptions{Namespace: nSvc.Namespace})) + if err != nil { + continue + } + if len(svcRegistrations) == 0 { + continue + } + newIndexes[s.ServiceName] = meta.LastIndex + services = append(services, &nomadService{ + name: fmt.Sprintf("%s-%s", svcRegistrations[0].Namespace, s.ServiceName), + params: n.params, + servers: n.convertToServers(svcRegistrations), + changed: n.hasServiceChanged(s.ServiceName, meta.LastIndex), + }) + + } + } + n.prevIndexes = newIndexes + return n.discoveryConfig.UpdateServices(services) +} + +func (n *nomadInstance) convertToServers(nodes []*api.ServiceRegistration) []configuration.ServiceServer { + servers := make([]configuration.ServiceServer, 0) + for _, node := range nodes { + servers = append(servers, configuration.ServiceServer{ + Address: node.Address, + Port: node.Port, + }) + } + return servers +} + +func (n *nomadInstance) hasServiceChanged(service string, index uint64) bool { + prevIndex, ok := n.prevIndexes[service] + if !ok { + return true + } + return prevIndex == index +} + +func (n *nomadInstance) updateTimeout(timeoutSeconds int) error { + timeout, err := time.ParseDuration(fmt.Sprintf("%ds", timeoutSeconds)) + if err != nil { + return err + } + n.timeout = timeout + return nil +} + +func (n *nomadInstance) handleStateChange() error { + if n.stateChangedToEnabled() { + if err := n.start(); err != nil { + n.prevEnabled = false + return err + } + n.prevEnabled = *n.params.Enabled + return nil + } + if n.stateChangedToDisabled() { + n.stop() + } + if *n.params.Enabled { + n.update <- struct{}{} + } + n.prevEnabled = *n.params.Enabled + return nil +} + +func (n *nomadInstance) stateChangedToEnabled() bool { + return !n.prevEnabled && *n.params.Enabled +} + +func (n *nomadInstance) stateChangedToDisabled() bool { + return n.prevEnabled && !*n.params.Enabled +} + +func (n *nomadInstance) logDebug(message string) { + log.WithFields(n.logFields, log.DebugLevel, message) +} + +func (n *nomadInstance) logErrorf(format string, args ...interface{}) { + log.WithFieldsf(n.logFields, log.ErrorLevel, format, args...) +} diff --git a/discovery/service_discovery.go b/discovery/service_discovery.go index cc34ba64..3803e1bd 100644 --- a/discovery/service_discovery.go +++ b/discovery/service_discovery.go @@ -61,6 +61,7 @@ func NewServiceDiscoveries(params ServiceDiscoveriesParams) ServiceDiscoveries { //nolint sd.AddService("consul", NewConsulDiscoveryService(params)) _ = sd.AddService("aws", NewAWSDiscoveryService(params)) + _ = sd.AddService("nomad", NewNomadDiscoveryService(params)) return sd } diff --git a/discovery/utils.go b/discovery/utils.go index 448df3cf..17004c21 100644 --- a/discovery/utils.go +++ b/discovery/utils.go @@ -78,6 +78,31 @@ func ValidateConsulData(data *models.Consul, useValidation bool) error { return nil } +func ValidateNomadData(data *models.Nomad, useValidation bool) error { + if useValidation { + validationErr := data.Validate(strfmt.Default) + if validationErr != nil { + return validationErr + } + } + if data.ID == nil || *data.ID == "" { + return errors.New("missing ID") + } + if _, err := uuid.Parse(*data.ID); err != nil { + return err + } + if data.ServerSlotsBase == nil || *data.ServerSlotsBase < minimumServerSlotsBase { + data.ServerSlotsBase = misc.Int64P(minimumServerSlotsBase) + } + if data.ServerSlotsGrowthType == nil { + data.ServerSlotsGrowthType = misc.StringP(models.ConsulServerSlotsGrowthTypeLinear) + } + if *data.ServerSlotsGrowthType == models.ConsulServerSlotsGrowthTypeLinear && (data.ServerSlotsGrowthIncrement == 0 || data.ServerSlotsGrowthIncrement < minimumServerSlotsBase) { + data.ServerSlotsGrowthIncrement = minimumServerSlotsBase + } + return nil +} + func NewServiceDiscoveryUUID() *string { id := uuid.New().String() return &id diff --git a/embedded_spec.go b/embedded_spec.go index b4a10a75..802f010c 100644 --- a/embedded_spec.go +++ b/embedded_spec.go @@ -639,6 +639,178 @@ func init() { } } }, + "/service_discovery/nomad": { + "get": { + "description": "Returns all configured Nomad servers.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Return an array of all configured Nomad servers", + "operationId": "getNomads", + "responses": { + "200": { + "description": "Successful operation", + "schema": { + "type": "object", + "required": [ + "data" + ], + "properties": { + "data": { + "$ref": "#/definitions/nomads" + } + } + } + }, + "default": { + "$ref": "#/responses/DefaultError" + } + } + }, + "post": { + "description": "Adds a new Nomad server.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Add a new Nomad server", + "operationId": "createNomad", + "parameters": [ + { + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/nomad" + } + } + ], + "responses": { + "201": { + "description": "Nomad created", + "schema": { + "$ref": "#/definitions/nomad" + } + }, + "400": { + "$ref": "#/responses/BadRequest" + }, + "409": { + "$ref": "#/responses/AlreadyExists" + }, + "default": { + "$ref": "#/responses/DefaultError" + } + } + } + }, + "/service_discovery/nomad/{id}": { + "get": { + "description": "Returns one Nomad server configuration by it's id.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Return one Nomad server", + "operationId": "getNomad", + "parameters": [ + { + "type": "string", + "description": "Nomad server id", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Successful operation", + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/nomad" + } + } + } + }, + "404": { + "$ref": "#/responses/NotFound" + }, + "default": { + "$ref": "#/responses/DefaultError" + } + } + }, + "put": { + "description": "Replaces a Nomad server configuration by it's id.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Replace a Nomad server", + "operationId": "replaceNomad", + "parameters": [ + { + "type": "string", + "description": "Nomad Index", + "name": "id", + "in": "path", + "required": true + }, + { + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/nomad" + } + } + ], + "responses": { + "200": { + "description": "Nomad server replaced", + "schema": { + "$ref": "#/definitions/nomad" + } + }, + "400": { + "$ref": "#/responses/BadRequest" + }, + "404": { + "$ref": "#/responses/NotFound" + }, + "default": { + "$ref": "#/responses/DefaultError" + } + } + }, + "delete": { + "description": "Deletes a Nomad server configuration by it's id.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Delete a Nomad server", + "operationId": "deleteNomad", + "parameters": [ + { + "type": "string", + "description": "Nomad server Index", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "Nomad server deleted" + }, + "404": { + "$ref": "#/responses/NotFound" + }, + "default": { + "$ref": "#/responses/DefaultError" + } + } + } + }, "/services": { "get": { "description": "Returns a list of API managed services endpoints.", @@ -21820,6 +21992,102 @@ func init() { } } }, + "nomad": { + "description": "Nomad server configuration", + "type": "object", + "title": "Nomad server", + "required": [ + "address", + "port", + "enabled", + "retry_timeout" + ], + "properties": { + "address": { + "type": "string", + "pattern": "^[^\\s]+$" + }, + "allowlist": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[^\\s]+$" + } + }, + "denylist": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[^\\s]+$" + } + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "id": { + "description": "Auto generated ID.", + "type": "string", + "pattern": "^[^\\s]+$", + "x-nullable": true + }, + "name": { + "type": "string" + }, + "namespace": { + "type": "string" + }, + "port": { + "type": "integer", + "maximum": 65535, + "minimum": 1 + }, + "retry_timeout": { + "description": "Duration in seconds in-between data pulling requests to the nomad server", + "type": "integer", + "minimum": 1 + }, + "secret_id": { + "type": "string", + "pattern": "^[^\\s]+$" + }, + "server_slots_base": { + "type": "integer", + "default": 10 + }, + "server_slots_growth_increment": { + "type": "integer" + }, + "server_slots_growth_type": { + "type": "string", + "default": "exponential", + "enum": [ + "linear", + "exponential" + ] + } + }, + "additionalProperties": false, + "example": { + "address": "127.0.0.1", + "enabled": true, + "id": "0", + "port": 4646, + "retry_timeout": "10a", + "service_allowlist": null, + "service_denylist": null + } + }, + "nomads": { + "description": "Nomads array", + "type": "array", + "title": "Nomads", + "items": { + "$ref": "#/definitions/nomad" + } + }, "peer_entries": { "description": "HAProxy peer entries array", "type": "array", @@ -26269,6 +26537,277 @@ func init() { } } }, + "/service_discovery/nomad": { + "get": { + "description": "Returns all configured Nomad servers.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Return an array of all configured Nomad servers", + "operationId": "getNomads", + "responses": { + "200": { + "description": "Successful operation", + "schema": { + "type": "object", + "required": [ + "data" + ], + "properties": { + "data": { + "$ref": "#/definitions/nomads" + } + } + } + }, + "default": { + "description": "General Error", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + } + } + }, + "post": { + "description": "Adds a new Nomad server.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Add a new Nomad server", + "operationId": "createNomad", + "parameters": [ + { + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/nomad" + } + } + ], + "responses": { + "201": { + "description": "Nomad created", + "schema": { + "$ref": "#/definitions/nomad" + } + }, + "400": { + "description": "Bad request", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + }, + "409": { + "description": "The specified resource already exists", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + }, + "default": { + "description": "General Error", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + } + } + } + }, + "/service_discovery/nomad/{id}": { + "get": { + "description": "Returns one Nomad server configuration by it's id.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Return one Nomad server", + "operationId": "getNomad", + "parameters": [ + { + "type": "string", + "description": "Nomad server id", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Successful operation", + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/nomad" + } + } + } + }, + "404": { + "description": "The specified resource was not found", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + }, + "default": { + "description": "General Error", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + } + } + }, + "put": { + "description": "Replaces a Nomad server configuration by it's id.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Replace a Nomad server", + "operationId": "replaceNomad", + "parameters": [ + { + "type": "string", + "description": "Nomad Index", + "name": "id", + "in": "path", + "required": true + }, + { + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/nomad" + } + } + ], + "responses": { + "200": { + "description": "Nomad server replaced", + "schema": { + "$ref": "#/definitions/nomad" + } + }, + "400": { + "description": "Bad request", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + }, + "404": { + "description": "The specified resource was not found", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + }, + "default": { + "description": "General Error", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + } + } + }, + "delete": { + "description": "Deletes a Nomad server configuration by it's id.", + "tags": [ + "ServiceDiscovery" + ], + "summary": "Delete a Nomad server", + "operationId": "deleteNomad", + "parameters": [ + { + "type": "string", + "description": "Nomad server Index", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "204": { + "description": "Nomad server deleted" + }, + "404": { + "description": "The specified resource was not found", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + }, + "default": { + "description": "General Error", + "schema": { + "$ref": "#/definitions/error" + }, + "headers": { + "Configuration-Version": { + "type": "string", + "description": "Configuration file version" + } + } + } + } + } + }, "/services": { "get": { "description": "Returns a list of API managed services endpoints.", @@ -54657,6 +55196,102 @@ func init() { } } }, + "nomad": { + "description": "Nomad server configuration", + "type": "object", + "title": "Nomad server", + "required": [ + "address", + "port", + "enabled", + "retry_timeout" + ], + "properties": { + "address": { + "type": "string", + "pattern": "^[^\\s]+$" + }, + "allowlist": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[^\\s]+$" + } + }, + "denylist": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[^\\s]+$" + } + }, + "description": { + "type": "string" + }, + "enabled": { + "type": "boolean" + }, + "id": { + "description": "Auto generated ID.", + "type": "string", + "pattern": "^[^\\s]+$", + "x-nullable": true + }, + "name": { + "type": "string" + }, + "namespace": { + "type": "string" + }, + "port": { + "type": "integer", + "maximum": 65535, + "minimum": 1 + }, + "retry_timeout": { + "description": "Duration in seconds in-between data pulling requests to the nomad server", + "type": "integer", + "minimum": 1 + }, + "secret_id": { + "type": "string", + "pattern": "^[^\\s]+$" + }, + "server_slots_base": { + "type": "integer", + "default": 10 + }, + "server_slots_growth_increment": { + "type": "integer" + }, + "server_slots_growth_type": { + "type": "string", + "default": "exponential", + "enum": [ + "linear", + "exponential" + ] + } + }, + "additionalProperties": false, + "example": { + "address": "127.0.0.1", + "enabled": true, + "id": "0", + "port": 4646, + "retry_timeout": "10a", + "service_allowlist": [], + "service_denylist": [] + } + }, + "nomads": { + "description": "Nomads array", + "type": "array", + "title": "Nomads", + "items": { + "$ref": "#/definitions/nomad" + } + }, "peer_entries": { "description": "HAProxy peer entries array", "type": "array", diff --git a/generate/go-generate.go b/generate/go-generate.go deleted file mode 100644 index 735af7dd..00000000 --- a/generate/go-generate.go +++ /dev/null @@ -1,510 +0,0 @@ -// Copyright 2019 HAProxy Technologies -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -package main - -import ( - "errors" - "fmt" - "io/ioutil" - "log" - "os" - "os/exec" - "path" - "path/filepath" - "strconv" - "strings" - "text/template" - "unicode" -) - -var serverGroups = map[string]string{ - "EnabledListeners": "dataplaneapi", - "CleanupTimeout": "dataplaneapi", - "GracefulTimeout": "dataplaneapi", - "MaxHeaderSize": "dataplaneapi", - "SocketPath": "dataplaneapi", - "Host": "dataplaneapi", - "Port": "dataplaneapi", - "ListenLimit": "dataplaneapi", - "KeepAlive": "dataplaneapi", - "ReadTimeout": "dataplaneapi", - "WriteTimeout": "dataplaneapi", - "TLSHost": "tls", - "TLSPort": "tls", - "TLSCertificate": "tls", - "TLSCertificateKey": "tls", - "TLSCACertificate": "tls", - "TLSListenLimit": "tls", - "TLSKeepAlive": "tls", - "TLSReadTimeout": "tls", - "TLSWriteTimeout": "tls", -} - -var groupParents = map[string]string{ - "advertised": "dataplaneapi", - "userlist": "dataplaneapi", - "resources": "dataplaneapi", - "transaction": "dataplaneapi", - "tls": "dataplaneapi", - "user": "dataplaneapi", - "reload": "haproxy", - "syslog": "log", - "log_targets": "log", -} - -var itemDefaults = map[string]interface{}{ - "port": 80, - "listen_limit": 1024, - "tls_host": "null", - "tls_port": 6443, - "tls_certificate": "null", - "tls_key": "null", - "tls_ca": "null", - "tls_listen_limit": 10, - "tls_keep_alive": "1m", - "tls_read_timeout": "10s", - "tls_write_timeout": "10s", - "userlist_file": "null", - "backups_dir": "/tmp/backups", - "scheme": "http", -} - -type Attribute struct { - Name string - AttName string - Type string - Long string - FileName string - Short string - Default string - ENV string - Group string - StructName string - SpecName string - Save bool - Deprecated bool - IsHCLKey bool - Example string -} - -type ParseGroup struct { - OriginalGroup string - Name string - AttName string - MaxSize int - MaxTypeSize int - Parent string - Elements []string - Attributes []Attribute - HasACLKey bool - IsList bool -} - -type ParseData struct { - Groups []ParseGroup -} - -func readServerData(filePath string, pd *ParseData, structName string, attName string, groupName string, isList bool) { - typeStruct := fmt.Sprintf("type %s struct {", structName) - dat, err := ioutil.ReadFile(filePath) - if err != nil { - log.Panic(err) - } - lines := strings.Split(string(dat), "\n") - inside := false - for _, line := range lines { - if strings.HasPrefix(line, typeStruct) { - inside = true - continue - } - if strings.HasPrefix(line, "}") { - inside = false - continue - } - if inside && strings.Contains(line, "`") { - res, err := processLine(line) - if err != nil { - continue - } - if structName == "Server" { - group, ok := serverGroups[res.Name] - if !ok { - log.Panicf("group not defined for %s in serverGroups", res.Name) - } - res.Group = group - } - res.AttName = attName - res.StructName = structName - found := false - if groupName == "" { - groupName = res.Group - } - for i, g := range pd.Groups { - if g.Name == res.Group { - found = true - if res.IsHCLKey { - g.HasACLKey = true - } - g.Attributes = append(g.Attributes, res) - if g.MaxSize < len(res.Name) { - g.MaxSize = len(res.Name) - } - if g.MaxTypeSize < len(res.Type) { - g.MaxSize = len(res.Type) - } - pd.Groups[i] = g - break - } - } - if !found { - pd.Groups = append(pd.Groups, ParseGroup{ - OriginalGroup: structName, - Name: res.Group, - AttName: attName, - Parent: groupParents[res.Group], - MaxSize: len(res.Name), - MaxTypeSize: len(res.Type), - Attributes: []Attribute{res}, - IsList: isList, - HasACLKey: res.IsHCLKey, - }) - } - } - } -} - -func capitalize(str string) string { - if len(str) == 0 { - return "" - } - var res strings.Builder - parts := strings.FieldsFunc(str, split) - for _, part := range parts { - res.WriteString(capitalizeChunk(part)) - } - return res.String() -} - -func split(r rune) bool { - return r == '_' || r == '-' -} - -func capitalizeChunk(str string) string { - if len(str) == 0 { - return "" - } - result := []rune(str) - result[0] = unicode.ToUpper(result[0]) - return string(result) -} - -func stripAtomic(str string) string { - if len(str) == 0 { - return "" - } - if strings.HasPrefix(str, "Atomic") { - return strings.ToLower(strings.TrimPrefix(str, "Atomic")) - } - return str -} - -func isListItem(att Attribute) string { - if att.IsHCLKey { - return "- " - } - return " " -} - -func getExample(att Attribute) string { - if att.Example != "" { - if att.Type == "int" { - i, _ := strconv.ParseInt(att.Example, 10, 64) - return fmt.Sprintf("%d", i) - } - return att.Example - } - if att.Default != "" { - switch att.Type { - case "int", "int64": - return att.Default - default: - return fmt.Sprintf(`"%s"`, att.Default) - } - } - if att.Type == "bool" { - return `false` - } - if strings.HasPrefix(att.Type, "[]*models.") { - return `[]` - } - if v, ok := itemDefaults[att.FileName]; ok { - switch t := v.(type) { - case int: - return fmt.Sprintf("%d", v.(int)) - default: - return t.(string) - } - } - return "null" -} - -func getQuotedExample(att Attribute) string { - if att.Type == "int" || att.Type == "int64" { - switch { - case len(att.Example) > 0: - return att.Example - case len(att.Default) > 0: - return att.Default - } - } - if att.Type == "bool" || att.Type == "AtomicBool" { - if len(att.Example) == 0 { - return `false` - } - return att.Example - } - if strings.HasPrefix(att.Type, "[]*models.") { - return `[]` - } - if att.Example != "" { - return fmt.Sprintf(`"%s"`, att.Example) - } - if att.Default != "" { - return fmt.Sprintf(`"%s"`, att.Default) - } - if v, ok := itemDefaults[att.FileName]; ok { - switch v.(type) { - case int: - return fmt.Sprintf("%d", v) - default: - return fmt.Sprintf(`"%s"`, v) - } - } - return `"null"` -} - -func main() { - dir, err := filepath.Abs(filepath.Dir(os.Args[0])) - if err != nil { - log.Fatal(err) - } - if strings.HasSuffix(dir, "generate") { - dir, err = filepath.Abs(filepath.Dir(os.Args[0]) + "/..") - if err != nil { - log.Fatal(err) - } - } - if len(os.Args) > 1 { - dir = os.Args[1] - } - - pd := &ParseData{ - Groups: []ParseGroup{}, - } - - pd.Groups = append(pd.Groups, ParseGroup{ - Name: "", - AttName: "-", - Parent: "", - MaxSize: 4, - MaxTypeSize: 12, - Attributes: []Attribute{}, - }) - // ######################################## server.go - filePath := path.Join(dir, "server.go") - readServerData(filePath, pd, "Server", "", "", false) - // ######################################## configuration.go - filePath = path.Join(dir, "configuration", "configuration.go") - readServerData(filePath, pd, "Configuration", "-", "", false) - readServerData(filePath, pd, "User", "Users", "", true) - readServerData(filePath, pd, "HAProxyConfiguration", "HAProxy", "", false) - readServerData(filePath, pd, "APIConfiguration", "APIOptions", "", false) - readServerData(filePath, pd, "ServiceDiscovery", "ServiceDiscovery", "", false) - readServerData(filePath, pd, "ClusterConfiguration", "Cluster", "cluster", false) - readServerData(filePath, pd, "SyslogOptions", "Syslog", "", false) - readServerData(filePath, pd, "LoggingOptions", "Logging", "", false) - // readServerData(filePath, pd, "User", "User", "") - // ######################################## - - // prepare template function - funcMap := template.FuncMap{ - "Capitalize": capitalize, - "StripAtomic": stripAtomic, - "Example": getExample, - "QuotedExample": getQuotedExample, - "IsListItem": isListItem, - } - // create configuration_generated - templatePath := path.Join(dir, "generate", "configuration.tmpl") - tmpl, err := template.New("configuration.tmpl").Funcs(funcMap).ParseFiles(templatePath) - if err != nil { - log.Panic(err) - } - tmpl = tmpl.Funcs(funcMap) - filePath = path.Join(dir, "configuration", "configuration_generated.go") - f, err := os.Create(filePath) - if err != nil { - log.Panic(err) - } - defer f.Close() - err = tmpl.Execute(f, pd) - if err != nil { - log.Panic(err) - } - fmtFile(filePath) - // create dataplaneapi_generated - templatePath = path.Join(dir, "generate", "dataplaneapi.tmpl") - tmpl, err = template.New("dataplaneapi.tmpl").Funcs(funcMap).ParseFiles(templatePath) - if err != nil { - log.Panic(err) - } - tmpl = tmpl.Funcs(funcMap) - filePath = path.Join(dir, "dataplaneapi_generated.go") - f, err = os.Create(filePath) - if err != nil { - log.Panic(err) - } - defer f.Close() - err = tmpl.Execute(f, pd) - if err != nil { - log.Panic(err) - } - fmtFile(filePath) - // create configuration example yaml - templatePath = path.Join(dir, "generate", "configuration-example-yaml.tmpl") - tmpl, err = template.New("configuration-example-yaml.tmpl").Funcs(funcMap).ParseFiles(templatePath) - if err != nil { - log.Panic(err) - } - tmpl = tmpl.Funcs(funcMap) - filePath = path.Join(dir, "configuration/examples/example-full.yaml") - f, err = os.Create(filePath) - if err != nil { - log.Panic(err) - } - defer f.Close() - err = tmpl.Execute(f, pd) - if err != nil { - log.Panic(err) - } - // create configuration example hcl - templatePath = path.Join(dir, "generate", "configuration-example-hcl.tmpl") - tmpl, err = template.New("configuration-example-hcl.tmpl").Funcs(funcMap).ParseFiles(templatePath) - if err != nil { - log.Panic(err) - } - tmpl = tmpl.Funcs(funcMap) - filePath = path.Join(dir, "configuration/examples/example-full.hcl") - f, err = os.Create(filePath) - if err != nil { - log.Panic(err) - } - defer f.Close() - err = tmpl.Execute(f, pd) - if err != nil { - log.Panic(err) - } -} - -func splitBy(c rune) bool { - return c == ' ' || c == '\t' -} - -func processLine(line string) (Attribute, error) { - parts := strings.FieldsFunc(line, splitBy) - var longName string - var envName string - var shortName string - var defaultName string - var group string - var specName string - var save bool - var deprecated bool - var isHCLKey bool - var example string - for _, part := range parts[2:] { - if strings.Contains(part, "long:") { - p := strings.Split(part, `"`) - longName = p[1] - } - if strings.Contains(part, "env:") { - p := strings.Split(part, `"`) - envName = p[1] - } - if strings.Contains(part, "short:") { - p := strings.Split(part, `"`) - shortName = p[1] - } - if strings.Contains(part, "default:") { - p := strings.Split(part, `"`) - defaultName = p[1] - } - if strings.Contains(part, "example:") { - p := strings.Split(part, `"`) - example = p[1] - } - if strings.Contains(part, "group:") { - p := strings.Split(part, `"`) - group = p[1] - } - if strings.Contains(part, `save:"true"`) { - save = true - } - if strings.Contains(part, `deprecated:"true"`) { - deprecated = true - } - if strings.HasPrefix(part, `hcl:"`) && strings.Contains(part, `,key"`) { - isHCLKey = true - } - if strings.Contains(part, `yaml:"-"`) { - return Attribute{}, errors.New("ignore this attribute") - } else if strings.Contains(part, `yaml:"`) { - p := strings.Split(part, `"`) - if strings.Contains(part, `,omitempty`) { - p[1] = strings.Replace(p[1], ",omitempty", "", 1) - } - specName = p[1] - } - } - fileName := longName - if longName == "" { - fileName = specName - } - - // fmt.Println(parts[0], parts[1]) - return Attribute{ - Name: parts[0], - Type: parts[1], - Long: longName, - FileName: strings.ReplaceAll(fileName, "-", "_"), - ENV: envName, - Short: shortName, - Default: defaultName, - Group: group, - SpecName: specName, - Save: save, - Deprecated: deprecated, - IsHCLKey: isHCLKey, - Example: example, - }, nil -} - -func fmtFile(filename string) { - cmd := exec.Command("gofmt", "-s", "-w", filename) - err := cmd.Run() - if err != nil { - log.Fatalf("cmd.Run() failed with %s\n", err) - } -} diff --git a/go.mod b/go.mod index 8fe2a311..402c097f 100644 --- a/go.mod +++ b/go.mod @@ -26,6 +26,7 @@ require ( github.com/haproxytech/config-parser/v4 v4.0.0-rc4.0.20220823131539-deece35aeef7 github.com/hashicorp/consul/api v1.6.0 github.com/hashicorp/hcl v1.0.0 + github.com/hashicorp/nomad/api v0.0.0-20220913021043-79e177dada7b github.com/jessevdk/go-flags v1.5.0 github.com/json-iterator/go v1.1.12 github.com/lestrrat-go/apache-logformat v0.0.0-20210106032603-24d066f940f8 @@ -58,8 +59,10 @@ require ( github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/gofrs/flock v0.8.1 // indirect github.com/google/go-cmp v0.5.8 // indirect + github.com/gorilla/websocket v1.5.0 // indirect github.com/haproxytech/go-logger v1.1.0 // indirect - github.com/hashicorp/go-cleanhttp v0.5.1 // indirect + github.com/hashicorp/cronexpr v1.1.1 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-hclog v0.12.0 // indirect github.com/hashicorp/go-immutable-radix v1.0.0 // indirect github.com/hashicorp/go-rootcerts v1.0.2 // indirect @@ -88,3 +91,5 @@ require ( go.mongodb.org/mongo-driver v1.10.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) + +// replace github.com/haproxytech/client-native/v4 => ../client-native diff --git a/go.sum b/go.sum index 05e2a216..fb2435d4 100644 --- a/go.sum +++ b/go.sum @@ -135,8 +135,8 @@ github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/haproxytech/client-native/v4 v4.0.1-0.20220902093849-9f9f0f9bc108 h1:sr0RWAMWkEiCL60p2m2UODMsk6lfOFCBWBM81ZKbqHs= -github.com/haproxytech/client-native/v4 v4.0.1-0.20220902093849-9f9f0f9bc108/go.mod h1:+T2Vwo+0G6ePgWzqd4nt1mMs1en4DyKcuplumhoGmgY= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/haproxytech/client-native/v4 v4.0.1-0.20220906055746-774e618a3c36 h1:LWUShk/25Wrqc5A5Ca5L61/4Go172zX2UkgS9oFwwE8= github.com/haproxytech/client-native/v4 v4.0.1-0.20220906055746-774e618a3c36/go.mod h1:+T2Vwo+0G6ePgWzqd4nt1mMs1en4DyKcuplumhoGmgY= github.com/haproxytech/config-parser/v4 v4.0.0-rc4.0.20220823131539-deece35aeef7 h1:N9H5fLuSzdKyQaIZH7Od5FPZzAVtBPAxiQ9QX/XysN8= @@ -147,10 +147,13 @@ github.com/hashicorp/consul/api v1.6.0 h1:SZB2hQW8AcTOpfDmiVblQbijxzsRuiyy0JpHfa github.com/hashicorp/consul/api v1.6.0/go.mod h1:1NSuaUUkFaJzMasbfq/11wKYWSR67Xn6r2DXKhuDNFg= github.com/hashicorp/consul/sdk v0.6.0 h1:FfhMEkwvQl57CildXJyGHnwGGM4HMODGyfjGwNM1Vdw= github.com/hashicorp/consul/sdk v0.6.0/go.mod h1:fY08Y9z5SvJqevyZNy6WWPXiG3KwBPAvlcdx16zZ0fM= +github.com/hashicorp/cronexpr v1.1.1 h1:NJZDd87hGXjoZBdvyCF9mX4DCq5Wy7+A/w+A7q0wn6c= +github.com/hashicorp/cronexpr v1.1.1/go.mod h1:P4wA0KBl9C5q2hABiMO7cp6jcIg96CDh1Efb3g1PWA4= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v0.12.0 h1:d4QkX8FRTYaKaCZBoXYY8zJX2BXjWxurN/GA2tkrmZM= github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0= @@ -176,6 +179,8 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= github.com/hashicorp/memberlist v0.2.2 h1:5+RffWKwqJ71YPu9mWsF7ZOscZmwfasdA8kbdC7AO2g= github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= +github.com/hashicorp/nomad/api v0.0.0-20220913021043-79e177dada7b h1:1FdoRKgOtdAzX6ie+tMQSKx+5NjQg6kbmGRaMCzCYUI= +github.com/hashicorp/nomad/api v0.0.0-20220913021043-79e177dada7b/go.mod h1:Z0U0rpbh4Qlkgqu3iRDcfJBA+r3FgoeD1BfigmZhfzM= github.com/hashicorp/serf v0.9.3 h1:AVF6JDQQens6nMHT9OGERBvK0f8rPrAGILnsKLr6lzM= github.com/hashicorp/serf v0.9.3/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= @@ -240,8 +245,8 @@ github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKju github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= @@ -285,6 +290,7 @@ github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUt github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shirou/gopsutil v3.21.4+incompatible h1:fuHcTm5mX+wzo542cmYcV9RTGQLbnHLI5SyQ5ryTVck= github.com/shirou/gopsutil v3.21.4+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/shoenig/test v0.3.1 h1:dhGZztS6nQuvJ0o0RtUiQHaEO4hhArh/WmWwik3Ols0= github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= diff --git a/handlers/nomad.go b/handlers/nomad.go new file mode 100644 index 00000000..8fa60e5e --- /dev/null +++ b/handlers/nomad.go @@ -0,0 +1,163 @@ +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package handlers + +import ( + "errors" + + "github.com/go-openapi/runtime/middleware" + "github.com/haproxytech/client-native/v4/models" + + sc "github.com/haproxytech/dataplaneapi/discovery" + "github.com/haproxytech/dataplaneapi/misc" + "github.com/haproxytech/dataplaneapi/operations/service_discovery" +) + +// CreateNomadHandlerImpl implementation of the CreateNomadHandler interface using client-native client +type CreateNomadHandlerImpl struct { + Discovery sc.ServiceDiscoveries + UseValidation bool + PersistCallback func([]*models.Nomad) error +} + +// DeleteNomadHandlerImpl implementation of the DeleteNomadHandler interface using client-native client +type DeleteNomadHandlerImpl struct { + Discovery sc.ServiceDiscoveries + PersistCallback func([]*models.Nomad) error +} + +// GetNomadHandlerImpl implementation of the GetNomadHandler interface using client-native client +type GetNomadHandlerImpl struct { + Discovery sc.ServiceDiscoveries +} + +// GetNomadsHandlerImpl implementation of the GetNomadsHandler interface using client-native client +type GetNomadsHandlerImpl struct { + Discovery sc.ServiceDiscoveries +} + +// ReplaceNomadHandlerImpl implementation of the ReplaceNomadHandler interface using client-native client +type ReplaceNomadHandlerImpl struct { + Discovery sc.ServiceDiscoveries + UseValidation bool + PersistCallback func([]*models.Nomad) error +} + +// Handle executing the request and returning a response +func (c *CreateNomadHandlerImpl) Handle(params service_discovery.CreateNomadParams, principal interface{}) middleware.Responder { + params.Data.ID = sc.NewServiceDiscoveryUUID() + if err := sc.ValidateNomadData(params.Data, c.UseValidation); err != nil { + e := misc.HandleError(err) + return service_discovery.NewCreateNomadDefault(int(*e.Code)).WithPayload(e) + } + err := c.Discovery.AddNode("nomad", *params.Data.ID, params.Data) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewCreateNomadDefault(int(*e.Code)).WithPayload(e) + } + nomads, err := getNomads(c.Discovery) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewCreateNomadDefault(int(*e.Code)).WithPayload(e) + } + err = c.PersistCallback(nomads) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewCreateNomadDefault(int(*e.Code)).WithPayload(e) + } + return service_discovery.NewCreateNomadCreated().WithPayload(params.Data) +} + +// Handle executing the request and returning a response +func (c *DeleteNomadHandlerImpl) Handle(params service_discovery.DeleteNomadParams, principal interface{}) middleware.Responder { + err := c.Discovery.RemoveNode("nomad", params.ID) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewReplaceNomadDefault(int(*e.Code)).WithPayload(e) + } + nomads, err := getNomads(c.Discovery) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewDeleteNomadDefault(int(*e.Code)).WithPayload(e) + } + err = c.PersistCallback(nomads) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewDeleteNomadDefault(int(*e.Code)).WithPayload(e) + } + return service_discovery.NewDeleteNomadNoContent() +} + +// Handle executing the request and returning a response +func (c *GetNomadHandlerImpl) Handle(params service_discovery.GetNomadParams, principal interface{}) middleware.Responder { + nodes, err := c.Discovery.GetNode("nomad", params.ID) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewGetNomadsDefault(int(*e.Code)).WithPayload(e) + } + nomad, ok := nodes.(*models.Nomad) + if !ok { + e := misc.HandleError(errors.New("expected *models.Nomad")) + return service_discovery.NewGetNomadsDefault(int(*e.Code)).WithPayload(e) + } + return service_discovery.NewGetNomadOK().WithPayload(&service_discovery.GetNomadOKBody{Data: nomad}) +} + +// Handle executing the request and returning a response +func (c *GetNomadsHandlerImpl) Handle(params service_discovery.GetNomadsParams, principal interface{}) middleware.Responder { + nomads, err := getNomads(c.Discovery) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewGetNomadDefault(int(*e.Code)).WithPayload(e) + } + return service_discovery.NewGetNomadsOK().WithPayload(&service_discovery.GetNomadsOKBody{Data: nomads}) +} + +// Handle executing the request and returning a response +func (c *ReplaceNomadHandlerImpl) Handle(params service_discovery.ReplaceNomadParams, principal interface{}) middleware.Responder { + if err := sc.ValidateNomadData(params.Data, c.UseValidation); err != nil { + e := misc.HandleError(err) + return service_discovery.NewReplaceNomadDefault(int(*e.Code)).WithPayload(e) + } + err := c.Discovery.UpdateNode("nomad", *params.Data.ID, params.Data) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewReplaceNomadDefault(int(*e.Code)).WithPayload(e) + } + nomads, err := getNomads(c.Discovery) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewReplaceNomadDefault(int(*e.Code)).WithPayload(e) + } + err = c.PersistCallback(nomads) + if err != nil { + e := misc.HandleError(err) + return service_discovery.NewDeleteNomadDefault(int(*e.Code)).WithPayload(e) + } + return service_discovery.NewReplaceNomadOK().WithPayload(params.Data) +} + +func getNomads(discovery sc.ServiceDiscoveries) (models.Nomads, error) { + nodes, err := discovery.GetNodes("nomad") + if err != nil { + return nil, err + } + nomads, ok := nodes.(models.Nomads) + if !ok { + return nil, errors.New("expected models.Nomads") + } + return nomads, nil +} diff --git a/operations/data_plane_api.go b/operations/data_plane_api.go index 0746746d..ac2e5385 100644 --- a/operations/data_plane_api.go +++ b/operations/data_plane_api.go @@ -212,6 +212,9 @@ func NewDataPlaneAPI(spec *loads.Document) *DataPlaneAPI { NameserverCreateNameserverHandler: nameserver.CreateNameserverHandlerFunc(func(params nameserver.CreateNameserverParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation nameserver.CreateNameserver has not yet been implemented") }), + ServiceDiscoveryCreateNomadHandler: service_discovery.CreateNomadHandlerFunc(func(params service_discovery.CreateNomadParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation service_discovery.CreateNomad has not yet been implemented") + }), PeerCreatePeerHandler: peer.CreatePeerHandlerFunc(func(params peer.CreatePeerParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation peer.CreatePeer has not yet been implemented") }), @@ -344,6 +347,9 @@ func NewDataPlaneAPI(spec *loads.Document) *DataPlaneAPI { NameserverDeleteNameserverHandler: nameserver.DeleteNameserverHandlerFunc(func(params nameserver.DeleteNameserverParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation nameserver.DeleteNameserver has not yet been implemented") }), + ServiceDiscoveryDeleteNomadHandler: service_discovery.DeleteNomadHandlerFunc(func(params service_discovery.DeleteNomadParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation service_discovery.DeleteNomad has not yet been implemented") + }), PeerDeletePeerHandler: peer.DeletePeerHandlerFunc(func(params peer.DeletePeerParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation peer.DeletePeer has not yet been implemented") }), @@ -599,6 +605,12 @@ func NewDataPlaneAPI(spec *loads.Document) *DataPlaneAPI { NameserverGetNameserversHandler: nameserver.GetNameserversHandlerFunc(func(params nameserver.GetNameserversParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation nameserver.GetNameservers has not yet been implemented") }), + ServiceDiscoveryGetNomadHandler: service_discovery.GetNomadHandlerFunc(func(params service_discovery.GetNomadParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation service_discovery.GetNomad has not yet been implemented") + }), + ServiceDiscoveryGetNomadsHandler: service_discovery.GetNomadsHandlerFunc(func(params service_discovery.GetNomadsParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation service_discovery.GetNomads has not yet been implemented") + }), MapsGetOneRuntimeMapHandler: maps.GetOneRuntimeMapHandlerFunc(func(params maps.GetOneRuntimeMapParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation maps.GetOneRuntimeMap has not yet been implemented") }), @@ -860,6 +872,9 @@ func NewDataPlaneAPI(spec *loads.Document) *DataPlaneAPI { NameserverReplaceNameserverHandler: nameserver.ReplaceNameserverHandlerFunc(func(params nameserver.ReplaceNameserverParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation nameserver.ReplaceNameserver has not yet been implemented") }), + ServiceDiscoveryReplaceNomadHandler: service_discovery.ReplaceNomadHandlerFunc(func(params service_discovery.ReplaceNomadParams, principal interface{}) middleware.Responder { + return middleware.NotImplemented("operation service_discovery.ReplaceNomad has not yet been implemented") + }), PeerEntryReplacePeerEntryHandler: peer_entry.ReplacePeerEntryHandlerFunc(func(params peer_entry.ReplacePeerEntryParams, principal interface{}) middleware.Responder { return middleware.NotImplemented("operation peer_entry.ReplacePeerEntry has not yet been implemented") }), @@ -1060,6 +1075,8 @@ type DataPlaneAPI struct { MailersCreateMailersSectionHandler mailers.CreateMailersSectionHandler // NameserverCreateNameserverHandler sets the operation handler for the create nameserver operation NameserverCreateNameserverHandler nameserver.CreateNameserverHandler + // ServiceDiscoveryCreateNomadHandler sets the operation handler for the create nomad operation + ServiceDiscoveryCreateNomadHandler service_discovery.CreateNomadHandler // PeerCreatePeerHandler sets the operation handler for the create peer operation PeerCreatePeerHandler peer.CreatePeerHandler // PeerEntryCreatePeerEntryHandler sets the operation handler for the create peer entry operation @@ -1148,6 +1165,8 @@ type DataPlaneAPI struct { MailersDeleteMailersSectionHandler mailers.DeleteMailersSectionHandler // NameserverDeleteNameserverHandler sets the operation handler for the delete nameserver operation NameserverDeleteNameserverHandler nameserver.DeleteNameserverHandler + // ServiceDiscoveryDeleteNomadHandler sets the operation handler for the delete nomad operation + ServiceDiscoveryDeleteNomadHandler service_discovery.DeleteNomadHandler // PeerDeletePeerHandler sets the operation handler for the delete peer operation PeerDeletePeerHandler peer.DeletePeerHandler // PeerEntryDeletePeerEntryHandler sets the operation handler for the delete peer entry operation @@ -1318,6 +1337,10 @@ type DataPlaneAPI struct { NameserverGetNameserverHandler nameserver.GetNameserverHandler // NameserverGetNameserversHandler sets the operation handler for the get nameservers operation NameserverGetNameserversHandler nameserver.GetNameserversHandler + // ServiceDiscoveryGetNomadHandler sets the operation handler for the get nomad operation + ServiceDiscoveryGetNomadHandler service_discovery.GetNomadHandler + // ServiceDiscoveryGetNomadsHandler sets the operation handler for the get nomads operation + ServiceDiscoveryGetNomadsHandler service_discovery.GetNomadsHandler // MapsGetOneRuntimeMapHandler sets the operation handler for the get one runtime map operation MapsGetOneRuntimeMapHandler maps.GetOneRuntimeMapHandler // SpoeGetOneSpoeFileHandler sets the operation handler for the get one spoe file operation @@ -1492,6 +1515,8 @@ type DataPlaneAPI struct { MailerEntryReplaceMailerEntryHandler mailer_entry.ReplaceMailerEntryHandler // NameserverReplaceNameserverHandler sets the operation handler for the replace nameserver operation NameserverReplaceNameserverHandler nameserver.ReplaceNameserverHandler + // ServiceDiscoveryReplaceNomadHandler sets the operation handler for the replace nomad operation + ServiceDiscoveryReplaceNomadHandler service_discovery.ReplaceNomadHandler // PeerEntryReplacePeerEntryHandler sets the operation handler for the replace peer entry operation PeerEntryReplacePeerEntryHandler peer_entry.ReplacePeerEntryHandler // ResolverReplaceResolverHandler sets the operation handler for the replace resolver operation @@ -1729,6 +1754,9 @@ func (o *DataPlaneAPI) Validate() error { if o.NameserverCreateNameserverHandler == nil { unregistered = append(unregistered, "nameserver.CreateNameserverHandler") } + if o.ServiceDiscoveryCreateNomadHandler == nil { + unregistered = append(unregistered, "service_discovery.CreateNomadHandler") + } if o.PeerCreatePeerHandler == nil { unregistered = append(unregistered, "peer.CreatePeerHandler") } @@ -1861,6 +1889,9 @@ func (o *DataPlaneAPI) Validate() error { if o.NameserverDeleteNameserverHandler == nil { unregistered = append(unregistered, "nameserver.DeleteNameserverHandler") } + if o.ServiceDiscoveryDeleteNomadHandler == nil { + unregistered = append(unregistered, "service_discovery.DeleteNomadHandler") + } if o.PeerDeletePeerHandler == nil { unregistered = append(unregistered, "peer.DeletePeerHandler") } @@ -2116,6 +2147,12 @@ func (o *DataPlaneAPI) Validate() error { if o.NameserverGetNameserversHandler == nil { unregistered = append(unregistered, "nameserver.GetNameserversHandler") } + if o.ServiceDiscoveryGetNomadHandler == nil { + unregistered = append(unregistered, "service_discovery.GetNomadHandler") + } + if o.ServiceDiscoveryGetNomadsHandler == nil { + unregistered = append(unregistered, "service_discovery.GetNomadsHandler") + } if o.MapsGetOneRuntimeMapHandler == nil { unregistered = append(unregistered, "maps.GetOneRuntimeMapHandler") } @@ -2377,6 +2414,9 @@ func (o *DataPlaneAPI) Validate() error { if o.NameserverReplaceNameserverHandler == nil { unregistered = append(unregistered, "nameserver.ReplaceNameserverHandler") } + if o.ServiceDiscoveryReplaceNomadHandler == nil { + unregistered = append(unregistered, "service_discovery.ReplaceNomadHandler") + } if o.PeerEntryReplacePeerEntryHandler == nil { unregistered = append(unregistered, "peer_entry.ReplacePeerEntryHandler") } @@ -2686,6 +2726,10 @@ func (o *DataPlaneAPI) initHandlerCache() { if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) } + o.handlers["POST"]["/service_discovery/nomad"] = service_discovery.NewCreateNomad(o.context, o.ServiceDiscoveryCreateNomadHandler) + if o.handlers["POST"] == nil { + o.handlers["POST"] = make(map[string]http.Handler) + } o.handlers["POST"]["/services/haproxy/configuration/peer_section"] = peer.NewCreatePeer(o.context, o.PeerCreatePeerHandler) if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) @@ -2862,6 +2906,10 @@ func (o *DataPlaneAPI) initHandlerCache() { if o.handlers["DELETE"] == nil { o.handlers["DELETE"] = make(map[string]http.Handler) } + o.handlers["DELETE"]["/service_discovery/nomad/{id}"] = service_discovery.NewDeleteNomad(o.context, o.ServiceDiscoveryDeleteNomadHandler) + if o.handlers["DELETE"] == nil { + o.handlers["DELETE"] = make(map[string]http.Handler) + } o.handlers["DELETE"]["/services/haproxy/configuration/peer_section/{name}"] = peer.NewDeletePeer(o.context, o.PeerDeletePeerHandler) if o.handlers["DELETE"] == nil { o.handlers["DELETE"] = make(map[string]http.Handler) @@ -3202,6 +3250,14 @@ func (o *DataPlaneAPI) initHandlerCache() { if o.handlers["GET"] == nil { o.handlers["GET"] = make(map[string]http.Handler) } + o.handlers["GET"]["/service_discovery/nomad/{id}"] = service_discovery.NewGetNomad(o.context, o.ServiceDiscoveryGetNomadHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } + o.handlers["GET"]["/service_discovery/nomad"] = service_discovery.NewGetNomads(o.context, o.ServiceDiscoveryGetNomadsHandler) + if o.handlers["GET"] == nil { + o.handlers["GET"] = make(map[string]http.Handler) + } o.handlers["GET"]["/services/haproxy/runtime/maps/{name}"] = maps.NewGetOneRuntimeMap(o.context, o.MapsGetOneRuntimeMapHandler) if o.handlers["GET"] == nil { o.handlers["GET"] = make(map[string]http.Handler) @@ -3550,6 +3606,10 @@ func (o *DataPlaneAPI) initHandlerCache() { if o.handlers["PUT"] == nil { o.handlers["PUT"] = make(map[string]http.Handler) } + o.handlers["PUT"]["/service_discovery/nomad/{id}"] = service_discovery.NewReplaceNomad(o.context, o.ServiceDiscoveryReplaceNomadHandler) + if o.handlers["PUT"] == nil { + o.handlers["PUT"] = make(map[string]http.Handler) + } o.handlers["PUT"]["/services/haproxy/configuration/peer_entries/{name}"] = peer_entry.NewReplacePeerEntry(o.context, o.PeerEntryReplacePeerEntryHandler) if o.handlers["PUT"] == nil { o.handlers["PUT"] = make(map[string]http.Handler) diff --git a/operations/service_discovery/create_nomad.go b/operations/service_discovery/create_nomad.go new file mode 100644 index 00000000..2d3f6aa8 --- /dev/null +++ b/operations/service_discovery/create_nomad.go @@ -0,0 +1,86 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// CreateNomadHandlerFunc turns a function with the right signature into a create nomad handler +type CreateNomadHandlerFunc func(CreateNomadParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn CreateNomadHandlerFunc) Handle(params CreateNomadParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// CreateNomadHandler interface for that can handle valid create nomad params +type CreateNomadHandler interface { + Handle(CreateNomadParams, interface{}) middleware.Responder +} + +// NewCreateNomad creates a new http.Handler for the create nomad operation +func NewCreateNomad(ctx *middleware.Context, handler CreateNomadHandler) *CreateNomad { + return &CreateNomad{Context: ctx, Handler: handler} +} + +/* + CreateNomad swagger:route POST /service_discovery/nomad ServiceDiscovery createNomad + +# Add a new Nomad server + +Adds a new Nomad server. +*/ +type CreateNomad struct { + Context *middleware.Context + Handler CreateNomadHandler +} + +func (o *CreateNomad) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewCreateNomadParams() + 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.(interface{}) // this is really a interface{}, I promise + } + + 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/operations/service_discovery/create_nomad_parameters.go b/operations/service_discovery/create_nomad_parameters.go new file mode 100644 index 00000000..25ae7019 --- /dev/null +++ b/operations/service_discovery/create_nomad_parameters.go @@ -0,0 +1,93 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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/haproxytech/client-native/v4/models" +) + +// NewCreateNomadParams creates a new CreateNomadParams object +// +// There are no default values defined in the spec. +func NewCreateNomadParams() CreateNomadParams { + + return CreateNomadParams{} +} + +// CreateNomadParams contains all the bound params for the create nomad operation +// typically these are obtained from a http.Request +// +// swagger:parameters createNomad +type CreateNomadParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /* + Required: true + In: body + */ + Data *models.Nomad +} + +// 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 NewCreateNomadParams() beforehand. +func (o *CreateNomadParams) 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.Nomad + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("data", "body", "")) + } else { + res = append(res, errors.NewParseError("data", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Data = &body + } + } + } else { + res = append(res, errors.Required("data", "body", "")) + } + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/operations/service_discovery/create_nomad_responses.go b/operations/service_discovery/create_nomad_responses.go new file mode 100644 index 00000000..ada71cea --- /dev/null +++ b/operations/service_discovery/create_nomad_responses.go @@ -0,0 +1,289 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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/haproxytech/client-native/v4/models" +) + +// CreateNomadCreatedCode is the HTTP code returned for type CreateNomadCreated +const CreateNomadCreatedCode int = 201 + +/* +CreateNomadCreated Nomad created + +swagger:response createNomadCreated +*/ +type CreateNomadCreated struct { + + /* + In: Body + */ + Payload *models.Nomad `json:"body,omitempty"` +} + +// NewCreateNomadCreated creates CreateNomadCreated with default headers values +func NewCreateNomadCreated() *CreateNomadCreated { + + return &CreateNomadCreated{} +} + +// WithPayload adds the payload to the create nomad created response +func (o *CreateNomadCreated) WithPayload(payload *models.Nomad) *CreateNomadCreated { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create nomad created response +func (o *CreateNomadCreated) SetPayload(payload *models.Nomad) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateNomadCreated) 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 + } + } +} + +// CreateNomadBadRequestCode is the HTTP code returned for type CreateNomadBadRequest +const CreateNomadBadRequestCode int = 400 + +/* +CreateNomadBadRequest Bad request + +swagger:response createNomadBadRequest +*/ +type CreateNomadBadRequest struct { + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewCreateNomadBadRequest creates CreateNomadBadRequest with default headers values +func NewCreateNomadBadRequest() *CreateNomadBadRequest { + + return &CreateNomadBadRequest{} +} + +// WithConfigurationVersion adds the configurationVersion to the create nomad bad request response +func (o *CreateNomadBadRequest) WithConfigurationVersion(configurationVersion string) *CreateNomadBadRequest { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the create nomad bad request response +func (o *CreateNomadBadRequest) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the create nomad bad request response +func (o *CreateNomadBadRequest) WithPayload(payload *models.Error) *CreateNomadBadRequest { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create nomad bad request response +func (o *CreateNomadBadRequest) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateNomadBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + 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 + } + } +} + +// CreateNomadConflictCode is the HTTP code returned for type CreateNomadConflict +const CreateNomadConflictCode int = 409 + +/* +CreateNomadConflict The specified resource already exists + +swagger:response createNomadConflict +*/ +type CreateNomadConflict struct { + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewCreateNomadConflict creates CreateNomadConflict with default headers values +func NewCreateNomadConflict() *CreateNomadConflict { + + return &CreateNomadConflict{} +} + +// WithConfigurationVersion adds the configurationVersion to the create nomad conflict response +func (o *CreateNomadConflict) WithConfigurationVersion(configurationVersion string) *CreateNomadConflict { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the create nomad conflict response +func (o *CreateNomadConflict) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the create nomad conflict response +func (o *CreateNomadConflict) WithPayload(payload *models.Error) *CreateNomadConflict { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create nomad conflict response +func (o *CreateNomadConflict) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateNomadConflict) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + 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 + } + } +} + +/* +CreateNomadDefault General Error + +swagger:response createNomadDefault +*/ +type CreateNomadDefault struct { + _statusCode int + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewCreateNomadDefault creates CreateNomadDefault with default headers values +func NewCreateNomadDefault(code int) *CreateNomadDefault { + if code <= 0 { + code = 500 + } + + return &CreateNomadDefault{ + _statusCode: code, + } +} + +// WithStatusCode adds the status to the create nomad default response +func (o *CreateNomadDefault) WithStatusCode(code int) *CreateNomadDefault { + o._statusCode = code + return o +} + +// SetStatusCode sets the status to the create nomad default response +func (o *CreateNomadDefault) SetStatusCode(code int) { + o._statusCode = code +} + +// WithConfigurationVersion adds the configurationVersion to the create nomad default response +func (o *CreateNomadDefault) WithConfigurationVersion(configurationVersion string) *CreateNomadDefault { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the create nomad default response +func (o *CreateNomadDefault) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the create nomad default response +func (o *CreateNomadDefault) WithPayload(payload *models.Error) *CreateNomadDefault { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the create nomad default response +func (o *CreateNomadDefault) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *CreateNomadDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + rw.WriteHeader(o._statusCode) + 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/operations/service_discovery/create_nomad_urlbuilder.go b/operations/service_discovery/create_nomad_urlbuilder.go new file mode 100644 index 00000000..c1d19980 --- /dev/null +++ b/operations/service_discovery/create_nomad_urlbuilder.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// CreateNomadURL generates an URL for the create nomad operation +type CreateNomadURL 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 *CreateNomadURL) WithBasePath(bp string) *CreateNomadURL { + 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 *CreateNomadURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *CreateNomadURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/service_discovery/nomad" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v2" + } + _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 *CreateNomadURL) 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 *CreateNomadURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *CreateNomadURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on CreateNomadURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on CreateNomadURL") + } + + 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 *CreateNomadURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/operations/service_discovery/delete_nomad.go b/operations/service_discovery/delete_nomad.go new file mode 100644 index 00000000..39124d37 --- /dev/null +++ b/operations/service_discovery/delete_nomad.go @@ -0,0 +1,86 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// DeleteNomadHandlerFunc turns a function with the right signature into a delete nomad handler +type DeleteNomadHandlerFunc func(DeleteNomadParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn DeleteNomadHandlerFunc) Handle(params DeleteNomadParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// DeleteNomadHandler interface for that can handle valid delete nomad params +type DeleteNomadHandler interface { + Handle(DeleteNomadParams, interface{}) middleware.Responder +} + +// NewDeleteNomad creates a new http.Handler for the delete nomad operation +func NewDeleteNomad(ctx *middleware.Context, handler DeleteNomadHandler) *DeleteNomad { + return &DeleteNomad{Context: ctx, Handler: handler} +} + +/* + DeleteNomad swagger:route DELETE /service_discovery/nomad/{id} ServiceDiscovery deleteNomad + +# Delete a Nomad server + +Deletes a Nomad server configuration by it's id. +*/ +type DeleteNomad struct { + Context *middleware.Context + Handler DeleteNomadHandler +} + +func (o *DeleteNomad) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewDeleteNomadParams() + 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.(interface{}) // this is really a interface{}, I promise + } + + 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/operations/service_discovery/delete_nomad_parameters.go b/operations/service_discovery/delete_nomad_parameters.go new file mode 100644 index 00000000..5e882385 --- /dev/null +++ b/operations/service_discovery/delete_nomad_parameters.go @@ -0,0 +1,86 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// NewDeleteNomadParams creates a new DeleteNomadParams object +// +// There are no default values defined in the spec. +func NewDeleteNomadParams() DeleteNomadParams { + + return DeleteNomadParams{} +} + +// DeleteNomadParams contains all the bound params for the delete nomad operation +// typically these are obtained from a http.Request +// +// swagger:parameters deleteNomad +type DeleteNomadParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Nomad server Index + 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 NewDeleteNomadParams() beforehand. +func (o *DeleteNomadParams) 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 *DeleteNomadParams) 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/operations/service_discovery/delete_nomad_responses.go b/operations/service_discovery/delete_nomad_responses.go new file mode 100644 index 00000000..39d129eb --- /dev/null +++ b/operations/service_discovery/delete_nomad_responses.go @@ -0,0 +1,202 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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/haproxytech/client-native/v4/models" +) + +// DeleteNomadNoContentCode is the HTTP code returned for type DeleteNomadNoContent +const DeleteNomadNoContentCode int = 204 + +/* +DeleteNomadNoContent Nomad server deleted + +swagger:response deleteNomadNoContent +*/ +type DeleteNomadNoContent struct { +} + +// NewDeleteNomadNoContent creates DeleteNomadNoContent with default headers values +func NewDeleteNomadNoContent() *DeleteNomadNoContent { + + return &DeleteNomadNoContent{} +} + +// WriteResponse to the client +func (o *DeleteNomadNoContent) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(204) +} + +// DeleteNomadNotFoundCode is the HTTP code returned for type DeleteNomadNotFound +const DeleteNomadNotFoundCode int = 404 + +/* +DeleteNomadNotFound The specified resource was not found + +swagger:response deleteNomadNotFound +*/ +type DeleteNomadNotFound struct { + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewDeleteNomadNotFound creates DeleteNomadNotFound with default headers values +func NewDeleteNomadNotFound() *DeleteNomadNotFound { + + return &DeleteNomadNotFound{} +} + +// WithConfigurationVersion adds the configurationVersion to the delete nomad not found response +func (o *DeleteNomadNotFound) WithConfigurationVersion(configurationVersion string) *DeleteNomadNotFound { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the delete nomad not found response +func (o *DeleteNomadNotFound) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the delete nomad not found response +func (o *DeleteNomadNotFound) WithPayload(payload *models.Error) *DeleteNomadNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the delete nomad not found response +func (o *DeleteNomadNotFound) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DeleteNomadNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + 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 + } + } +} + +/* +DeleteNomadDefault General Error + +swagger:response deleteNomadDefault +*/ +type DeleteNomadDefault struct { + _statusCode int + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewDeleteNomadDefault creates DeleteNomadDefault with default headers values +func NewDeleteNomadDefault(code int) *DeleteNomadDefault { + if code <= 0 { + code = 500 + } + + return &DeleteNomadDefault{ + _statusCode: code, + } +} + +// WithStatusCode adds the status to the delete nomad default response +func (o *DeleteNomadDefault) WithStatusCode(code int) *DeleteNomadDefault { + o._statusCode = code + return o +} + +// SetStatusCode sets the status to the delete nomad default response +func (o *DeleteNomadDefault) SetStatusCode(code int) { + o._statusCode = code +} + +// WithConfigurationVersion adds the configurationVersion to the delete nomad default response +func (o *DeleteNomadDefault) WithConfigurationVersion(configurationVersion string) *DeleteNomadDefault { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the delete nomad default response +func (o *DeleteNomadDefault) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the delete nomad default response +func (o *DeleteNomadDefault) WithPayload(payload *models.Error) *DeleteNomadDefault { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the delete nomad default response +func (o *DeleteNomadDefault) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *DeleteNomadDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + rw.WriteHeader(o._statusCode) + 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/operations/service_discovery/delete_nomad_urlbuilder.go b/operations/service_discovery/delete_nomad_urlbuilder.go new file mode 100644 index 00000000..1344983b --- /dev/null +++ b/operations/service_discovery/delete_nomad_urlbuilder.go @@ -0,0 +1,114 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// DeleteNomadURL generates an URL for the delete nomad operation +type DeleteNomadURL 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 *DeleteNomadURL) WithBasePath(bp string) *DeleteNomadURL { + 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 *DeleteNomadURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *DeleteNomadURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/service_discovery/nomad/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on DeleteNomadURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v2" + } + _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 *DeleteNomadURL) 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 *DeleteNomadURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *DeleteNomadURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on DeleteNomadURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on DeleteNomadURL") + } + + 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 *DeleteNomadURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/operations/service_discovery/get_nomad.go b/operations/service_discovery/get_nomad.go new file mode 100644 index 00000000..1fc0dc83 --- /dev/null +++ b/operations/service_discovery/get_nomad.go @@ -0,0 +1,182 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "context" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "github.com/haproxytech/client-native/v4/models" +) + +// GetNomadHandlerFunc turns a function with the right signature into a get nomad handler +type GetNomadHandlerFunc func(GetNomadParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetNomadHandlerFunc) Handle(params GetNomadParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetNomadHandler interface for that can handle valid get nomad params +type GetNomadHandler interface { + Handle(GetNomadParams, interface{}) middleware.Responder +} + +// NewGetNomad creates a new http.Handler for the get nomad operation +func NewGetNomad(ctx *middleware.Context, handler GetNomadHandler) *GetNomad { + return &GetNomad{Context: ctx, Handler: handler} +} + +/* + GetNomad swagger:route GET /service_discovery/nomad/{id} ServiceDiscovery getNomad + +# Return one Nomad server + +Returns one Nomad server configuration by it's id. +*/ +type GetNomad struct { + Context *middleware.Context + Handler GetNomadHandler +} + +func (o *GetNomad) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewGetNomadParams() + 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.(interface{}) // this is really a interface{}, I promise + } + + 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) + +} + +// GetNomadOKBody get nomad o k body +// +// swagger:model GetNomadOKBody +type GetNomadOKBody struct { + + // data + Data *models.Nomad `json:"data,omitempty"` +} + +// Validate validates this get nomad o k body +func (o *GetNomadOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetNomadOKBody) validateData(formats strfmt.Registry) error { + if swag.IsZero(o.Data) { // not required + return nil + } + + if o.Data != nil { + if err := o.Data.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getNomadOK" + "." + "data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getNomadOK" + "." + "data") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get nomad o k body based on the context it is used +func (o *GetNomadOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetNomadOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + if o.Data != nil { + if err := o.Data.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getNomadOK" + "." + "data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getNomadOK" + "." + "data") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetNomadOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetNomadOKBody) UnmarshalBinary(b []byte) error { + var res GetNomadOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/operations/service_discovery/get_nomad_parameters.go b/operations/service_discovery/get_nomad_parameters.go new file mode 100644 index 00000000..df5cad2b --- /dev/null +++ b/operations/service_discovery/get_nomad_parameters.go @@ -0,0 +1,86 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// NewGetNomadParams creates a new GetNomadParams object +// +// There are no default values defined in the spec. +func NewGetNomadParams() GetNomadParams { + + return GetNomadParams{} +} + +// GetNomadParams contains all the bound params for the get nomad operation +// typically these are obtained from a http.Request +// +// swagger:parameters getNomad +type GetNomadParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /*Nomad server id + 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 NewGetNomadParams() beforehand. +func (o *GetNomadParams) 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 *GetNomadParams) 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/operations/service_discovery/get_nomad_responses.go b/operations/service_discovery/get_nomad_responses.go new file mode 100644 index 00000000..beca2e16 --- /dev/null +++ b/operations/service_discovery/get_nomad_responses.go @@ -0,0 +1,222 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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/haproxytech/client-native/v4/models" +) + +// GetNomadOKCode is the HTTP code returned for type GetNomadOK +const GetNomadOKCode int = 200 + +/* +GetNomadOK Successful operation + +swagger:response getNomadOK +*/ +type GetNomadOK struct { + + /* + In: Body + */ + Payload *GetNomadOKBody `json:"body,omitempty"` +} + +// NewGetNomadOK creates GetNomadOK with default headers values +func NewGetNomadOK() *GetNomadOK { + + return &GetNomadOK{} +} + +// WithPayload adds the payload to the get nomad o k response +func (o *GetNomadOK) WithPayload(payload *GetNomadOKBody) *GetNomadOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get nomad o k response +func (o *GetNomadOK) SetPayload(payload *GetNomadOKBody) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetNomadOK) 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 + } + } +} + +// GetNomadNotFoundCode is the HTTP code returned for type GetNomadNotFound +const GetNomadNotFoundCode int = 404 + +/* +GetNomadNotFound The specified resource was not found + +swagger:response getNomadNotFound +*/ +type GetNomadNotFound struct { + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewGetNomadNotFound creates GetNomadNotFound with default headers values +func NewGetNomadNotFound() *GetNomadNotFound { + + return &GetNomadNotFound{} +} + +// WithConfigurationVersion adds the configurationVersion to the get nomad not found response +func (o *GetNomadNotFound) WithConfigurationVersion(configurationVersion string) *GetNomadNotFound { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the get nomad not found response +func (o *GetNomadNotFound) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the get nomad not found response +func (o *GetNomadNotFound) WithPayload(payload *models.Error) *GetNomadNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get nomad not found response +func (o *GetNomadNotFound) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetNomadNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + 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 + } + } +} + +/* +GetNomadDefault General Error + +swagger:response getNomadDefault +*/ +type GetNomadDefault struct { + _statusCode int + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewGetNomadDefault creates GetNomadDefault with default headers values +func NewGetNomadDefault(code int) *GetNomadDefault { + if code <= 0 { + code = 500 + } + + return &GetNomadDefault{ + _statusCode: code, + } +} + +// WithStatusCode adds the status to the get nomad default response +func (o *GetNomadDefault) WithStatusCode(code int) *GetNomadDefault { + o._statusCode = code + return o +} + +// SetStatusCode sets the status to the get nomad default response +func (o *GetNomadDefault) SetStatusCode(code int) { + o._statusCode = code +} + +// WithConfigurationVersion adds the configurationVersion to the get nomad default response +func (o *GetNomadDefault) WithConfigurationVersion(configurationVersion string) *GetNomadDefault { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the get nomad default response +func (o *GetNomadDefault) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the get nomad default response +func (o *GetNomadDefault) WithPayload(payload *models.Error) *GetNomadDefault { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get nomad default response +func (o *GetNomadDefault) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetNomadDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + rw.WriteHeader(o._statusCode) + 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/operations/service_discovery/get_nomad_urlbuilder.go b/operations/service_discovery/get_nomad_urlbuilder.go new file mode 100644 index 00000000..7eb35e17 --- /dev/null +++ b/operations/service_discovery/get_nomad_urlbuilder.go @@ -0,0 +1,114 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// GetNomadURL generates an URL for the get nomad operation +type GetNomadURL 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 *GetNomadURL) WithBasePath(bp string) *GetNomadURL { + 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 *GetNomadURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetNomadURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/service_discovery/nomad/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on GetNomadURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v2" + } + _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 *GetNomadURL) 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 *GetNomadURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetNomadURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetNomadURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetNomadURL") + } + + 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 *GetNomadURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/operations/service_discovery/get_nomads.go b/operations/service_discovery/get_nomads.go new file mode 100644 index 00000000..acf41173 --- /dev/null +++ b/operations/service_discovery/get_nomads.go @@ -0,0 +1,181 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the generate command + +import ( + "context" + "net/http" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime/middleware" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" + + "github.com/haproxytech/client-native/v4/models" +) + +// GetNomadsHandlerFunc turns a function with the right signature into a get nomads handler +type GetNomadsHandlerFunc func(GetNomadsParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn GetNomadsHandlerFunc) Handle(params GetNomadsParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// GetNomadsHandler interface for that can handle valid get nomads params +type GetNomadsHandler interface { + Handle(GetNomadsParams, interface{}) middleware.Responder +} + +// NewGetNomads creates a new http.Handler for the get nomads operation +func NewGetNomads(ctx *middleware.Context, handler GetNomadsHandler) *GetNomads { + return &GetNomads{Context: ctx, Handler: handler} +} + +/* + GetNomads swagger:route GET /service_discovery/nomad ServiceDiscovery getNomads + +# Return an array of all configured Nomad servers + +Returns all configured Nomad servers. +*/ +type GetNomads struct { + Context *middleware.Context + Handler GetNomadsHandler +} + +func (o *GetNomads) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewGetNomadsParams() + 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.(interface{}) // this is really a interface{}, I promise + } + + 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) + +} + +// GetNomadsOKBody get nomads o k body +// +// swagger:model GetNomadsOKBody +type GetNomadsOKBody struct { + + // data + // Required: true + Data models.Nomads `json:"data"` +} + +// Validate validates this get nomads o k body +func (o *GetNomadsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetNomadsOKBody) validateData(formats strfmt.Registry) error { + + if err := validate.Required("getNomadsOK"+"."+"data", "body", o.Data); err != nil { + return err + } + + if err := o.Data.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getNomadsOK" + "." + "data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getNomadsOK" + "." + "data") + } + return err + } + + return nil +} + +// ContextValidate validate this get nomads o k body based on the context it is used +func (o *GetNomadsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetNomadsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + if err := o.Data.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getNomadsOK" + "." + "data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getNomadsOK" + "." + "data") + } + return err + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetNomadsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetNomadsOKBody) UnmarshalBinary(b []byte) error { + var res GetNomadsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/operations/service_discovery/get_nomads_parameters.go b/operations/service_discovery/get_nomads_parameters.go new file mode 100644 index 00000000..dfe095ac --- /dev/null +++ b/operations/service_discovery/get_nomads_parameters.go @@ -0,0 +1,61 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// NewGetNomadsParams creates a new GetNomadsParams object +// +// There are no default values defined in the spec. +func NewGetNomadsParams() GetNomadsParams { + + return GetNomadsParams{} +} + +// GetNomadsParams contains all the bound params for the get nomads operation +// typically these are obtained from a http.Request +// +// swagger:parameters getNomads +type GetNomadsParams 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 NewGetNomadsParams() beforehand. +func (o *GetNomadsParams) 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/operations/service_discovery/get_nomads_responses.go b/operations/service_discovery/get_nomads_responses.go new file mode 100644 index 00000000..c5652668 --- /dev/null +++ b/operations/service_discovery/get_nomads_responses.go @@ -0,0 +1,155 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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/haproxytech/client-native/v4/models" +) + +// GetNomadsOKCode is the HTTP code returned for type GetNomadsOK +const GetNomadsOKCode int = 200 + +/* +GetNomadsOK Successful operation + +swagger:response getNomadsOK +*/ +type GetNomadsOK struct { + + /* + In: Body + */ + Payload *GetNomadsOKBody `json:"body,omitempty"` +} + +// NewGetNomadsOK creates GetNomadsOK with default headers values +func NewGetNomadsOK() *GetNomadsOK { + + return &GetNomadsOK{} +} + +// WithPayload adds the payload to the get nomads o k response +func (o *GetNomadsOK) WithPayload(payload *GetNomadsOKBody) *GetNomadsOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get nomads o k response +func (o *GetNomadsOK) SetPayload(payload *GetNomadsOKBody) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetNomadsOK) 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 + } + } +} + +/* +GetNomadsDefault General Error + +swagger:response getNomadsDefault +*/ +type GetNomadsDefault struct { + _statusCode int + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewGetNomadsDefault creates GetNomadsDefault with default headers values +func NewGetNomadsDefault(code int) *GetNomadsDefault { + if code <= 0 { + code = 500 + } + + return &GetNomadsDefault{ + _statusCode: code, + } +} + +// WithStatusCode adds the status to the get nomads default response +func (o *GetNomadsDefault) WithStatusCode(code int) *GetNomadsDefault { + o._statusCode = code + return o +} + +// SetStatusCode sets the status to the get nomads default response +func (o *GetNomadsDefault) SetStatusCode(code int) { + o._statusCode = code +} + +// WithConfigurationVersion adds the configurationVersion to the get nomads default response +func (o *GetNomadsDefault) WithConfigurationVersion(configurationVersion string) *GetNomadsDefault { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the get nomads default response +func (o *GetNomadsDefault) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the get nomads default response +func (o *GetNomadsDefault) WithPayload(payload *models.Error) *GetNomadsDefault { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the get nomads default response +func (o *GetNomadsDefault) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *GetNomadsDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + rw.WriteHeader(o._statusCode) + 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/operations/service_discovery/get_nomads_urlbuilder.go b/operations/service_discovery/get_nomads_urlbuilder.go new file mode 100644 index 00000000..2b59c10f --- /dev/null +++ b/operations/service_discovery/get_nomads_urlbuilder.go @@ -0,0 +1,102 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// GetNomadsURL generates an URL for the get nomads operation +type GetNomadsURL 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 *GetNomadsURL) WithBasePath(bp string) *GetNomadsURL { + 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 *GetNomadsURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *GetNomadsURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/service_discovery/nomad" + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v2" + } + _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 *GetNomadsURL) 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 *GetNomadsURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *GetNomadsURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on GetNomadsURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on GetNomadsURL") + } + + 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 *GetNomadsURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +} diff --git a/operations/service_discovery/replace_nomad.go b/operations/service_discovery/replace_nomad.go new file mode 100644 index 00000000..baa6522a --- /dev/null +++ b/operations/service_discovery/replace_nomad.go @@ -0,0 +1,86 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// ReplaceNomadHandlerFunc turns a function with the right signature into a replace nomad handler +type ReplaceNomadHandlerFunc func(ReplaceNomadParams, interface{}) middleware.Responder + +// Handle executing the request and returning a response +func (fn ReplaceNomadHandlerFunc) Handle(params ReplaceNomadParams, principal interface{}) middleware.Responder { + return fn(params, principal) +} + +// ReplaceNomadHandler interface for that can handle valid replace nomad params +type ReplaceNomadHandler interface { + Handle(ReplaceNomadParams, interface{}) middleware.Responder +} + +// NewReplaceNomad creates a new http.Handler for the replace nomad operation +func NewReplaceNomad(ctx *middleware.Context, handler ReplaceNomadHandler) *ReplaceNomad { + return &ReplaceNomad{Context: ctx, Handler: handler} +} + +/* + ReplaceNomad swagger:route PUT /service_discovery/nomad/{id} ServiceDiscovery replaceNomad + +# Replace a Nomad server + +Replaces a Nomad server configuration by it's id. +*/ +type ReplaceNomad struct { + Context *middleware.Context + Handler ReplaceNomadHandler +} + +func (o *ReplaceNomad) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + route, rCtx, _ := o.Context.RouteInfo(r) + if rCtx != nil { + *r = *rCtx + } + var Params = NewReplaceNomadParams() + 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.(interface{}) // this is really a interface{}, I promise + } + + 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/operations/service_discovery/replace_nomad_parameters.go b/operations/service_discovery/replace_nomad_parameters.go new file mode 100644 index 00000000..5a00d370 --- /dev/null +++ b/operations/service_discovery/replace_nomad_parameters.go @@ -0,0 +1,118 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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/haproxytech/client-native/v4/models" +) + +// NewReplaceNomadParams creates a new ReplaceNomadParams object +// +// There are no default values defined in the spec. +func NewReplaceNomadParams() ReplaceNomadParams { + + return ReplaceNomadParams{} +} + +// ReplaceNomadParams contains all the bound params for the replace nomad operation +// typically these are obtained from a http.Request +// +// swagger:parameters replaceNomad +type ReplaceNomadParams struct { + + // HTTP Request Object + HTTPRequest *http.Request `json:"-"` + + /* + Required: true + In: body + */ + Data *models.Nomad + /*Nomad Index + 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 NewReplaceNomadParams() beforehand. +func (o *ReplaceNomadParams) 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.Nomad + if err := route.Consumer.Consume(r.Body, &body); err != nil { + if err == io.EOF { + res = append(res, errors.Required("data", "body", "")) + } else { + res = append(res, errors.NewParseError("data", "body", "", err)) + } + } else { + // validate body object + if err := body.Validate(route.Formats); err != nil { + res = append(res, err) + } + + if len(res) == 0 { + o.Data = &body + } + } + } else { + res = append(res, errors.Required("data", "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 *ReplaceNomadParams) 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/operations/service_discovery/replace_nomad_responses.go b/operations/service_discovery/replace_nomad_responses.go new file mode 100644 index 00000000..b72208c1 --- /dev/null +++ b/operations/service_discovery/replace_nomad_responses.go @@ -0,0 +1,289 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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/haproxytech/client-native/v4/models" +) + +// ReplaceNomadOKCode is the HTTP code returned for type ReplaceNomadOK +const ReplaceNomadOKCode int = 200 + +/* +ReplaceNomadOK Nomad server replaced + +swagger:response replaceNomadOK +*/ +type ReplaceNomadOK struct { + + /* + In: Body + */ + Payload *models.Nomad `json:"body,omitempty"` +} + +// NewReplaceNomadOK creates ReplaceNomadOK with default headers values +func NewReplaceNomadOK() *ReplaceNomadOK { + + return &ReplaceNomadOK{} +} + +// WithPayload adds the payload to the replace nomad o k response +func (o *ReplaceNomadOK) WithPayload(payload *models.Nomad) *ReplaceNomadOK { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the replace nomad o k response +func (o *ReplaceNomadOK) SetPayload(payload *models.Nomad) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReplaceNomadOK) 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 + } + } +} + +// ReplaceNomadBadRequestCode is the HTTP code returned for type ReplaceNomadBadRequest +const ReplaceNomadBadRequestCode int = 400 + +/* +ReplaceNomadBadRequest Bad request + +swagger:response replaceNomadBadRequest +*/ +type ReplaceNomadBadRequest struct { + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewReplaceNomadBadRequest creates ReplaceNomadBadRequest with default headers values +func NewReplaceNomadBadRequest() *ReplaceNomadBadRequest { + + return &ReplaceNomadBadRequest{} +} + +// WithConfigurationVersion adds the configurationVersion to the replace nomad bad request response +func (o *ReplaceNomadBadRequest) WithConfigurationVersion(configurationVersion string) *ReplaceNomadBadRequest { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the replace nomad bad request response +func (o *ReplaceNomadBadRequest) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the replace nomad bad request response +func (o *ReplaceNomadBadRequest) WithPayload(payload *models.Error) *ReplaceNomadBadRequest { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the replace nomad bad request response +func (o *ReplaceNomadBadRequest) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReplaceNomadBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + 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 + } + } +} + +// ReplaceNomadNotFoundCode is the HTTP code returned for type ReplaceNomadNotFound +const ReplaceNomadNotFoundCode int = 404 + +/* +ReplaceNomadNotFound The specified resource was not found + +swagger:response replaceNomadNotFound +*/ +type ReplaceNomadNotFound struct { + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewReplaceNomadNotFound creates ReplaceNomadNotFound with default headers values +func NewReplaceNomadNotFound() *ReplaceNomadNotFound { + + return &ReplaceNomadNotFound{} +} + +// WithConfigurationVersion adds the configurationVersion to the replace nomad not found response +func (o *ReplaceNomadNotFound) WithConfigurationVersion(configurationVersion string) *ReplaceNomadNotFound { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the replace nomad not found response +func (o *ReplaceNomadNotFound) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the replace nomad not found response +func (o *ReplaceNomadNotFound) WithPayload(payload *models.Error) *ReplaceNomadNotFound { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the replace nomad not found response +func (o *ReplaceNomadNotFound) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReplaceNomadNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + 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 + } + } +} + +/* +ReplaceNomadDefault General Error + +swagger:response replaceNomadDefault +*/ +type ReplaceNomadDefault struct { + _statusCode int + /*Configuration file version + + */ + ConfigurationVersion string `json:"Configuration-Version"` + + /* + In: Body + */ + Payload *models.Error `json:"body,omitempty"` +} + +// NewReplaceNomadDefault creates ReplaceNomadDefault with default headers values +func NewReplaceNomadDefault(code int) *ReplaceNomadDefault { + if code <= 0 { + code = 500 + } + + return &ReplaceNomadDefault{ + _statusCode: code, + } +} + +// WithStatusCode adds the status to the replace nomad default response +func (o *ReplaceNomadDefault) WithStatusCode(code int) *ReplaceNomadDefault { + o._statusCode = code + return o +} + +// SetStatusCode sets the status to the replace nomad default response +func (o *ReplaceNomadDefault) SetStatusCode(code int) { + o._statusCode = code +} + +// WithConfigurationVersion adds the configurationVersion to the replace nomad default response +func (o *ReplaceNomadDefault) WithConfigurationVersion(configurationVersion string) *ReplaceNomadDefault { + o.ConfigurationVersion = configurationVersion + return o +} + +// SetConfigurationVersion sets the configurationVersion to the replace nomad default response +func (o *ReplaceNomadDefault) SetConfigurationVersion(configurationVersion string) { + o.ConfigurationVersion = configurationVersion +} + +// WithPayload adds the payload to the replace nomad default response +func (o *ReplaceNomadDefault) WithPayload(payload *models.Error) *ReplaceNomadDefault { + o.Payload = payload + return o +} + +// SetPayload sets the payload to the replace nomad default response +func (o *ReplaceNomadDefault) SetPayload(payload *models.Error) { + o.Payload = payload +} + +// WriteResponse to the client +func (o *ReplaceNomadDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + // response header Configuration-Version + + configurationVersion := o.ConfigurationVersion + if configurationVersion != "" { + rw.Header().Set("Configuration-Version", configurationVersion) + } + + rw.WriteHeader(o._statusCode) + 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/operations/service_discovery/replace_nomad_urlbuilder.go b/operations/service_discovery/replace_nomad_urlbuilder.go new file mode 100644 index 00000000..43d47ebe --- /dev/null +++ b/operations/service_discovery/replace_nomad_urlbuilder.go @@ -0,0 +1,114 @@ +// Code generated by go-swagger; DO NOT EDIT. + +// Copyright 2019 HAProxy Technologies +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +package service_discovery + +// 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" +) + +// ReplaceNomadURL generates an URL for the replace nomad operation +type ReplaceNomadURL 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 *ReplaceNomadURL) WithBasePath(bp string) *ReplaceNomadURL { + 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 *ReplaceNomadURL) SetBasePath(bp string) { + o._basePath = bp +} + +// Build a url path and query string +func (o *ReplaceNomadURL) Build() (*url.URL, error) { + var _result url.URL + + var _path = "/service_discovery/nomad/{id}" + + id := o.ID + if id != "" { + _path = strings.Replace(_path, "{id}", id, -1) + } else { + return nil, errors.New("id is required on ReplaceNomadURL") + } + + _basePath := o._basePath + if _basePath == "" { + _basePath = "/v2" + } + _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 *ReplaceNomadURL) 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 *ReplaceNomadURL) String() string { + return o.Must(o.Build()).String() +} + +// BuildFull builds a full url with scheme, host, path and query string +func (o *ReplaceNomadURL) BuildFull(scheme, host string) (*url.URL, error) { + if scheme == "" { + return nil, errors.New("scheme is required for a full url on ReplaceNomadURL") + } + if host == "" { + return nil, errors.New("host is required for a full url on ReplaceNomadURL") + } + + 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 *ReplaceNomadURL) StringFull(scheme, host string) string { + return o.Must(o.BuildFull(scheme, host)).String() +}