brokerapi

package module
v4.2.2+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 7, 2019 License: Apache-2.0 Imports: 13 Imported by: 312

README

brokerapi

Build Status

A Go package for building V2 Open Service Broker API compliant Service Brokers.

Docs

Dependencies

We use dep to manager our dependencies. Use dep ensure in order to download the required packages.

Usage

brokerapi defines a ServiceBroker interface. Pass an implementation of this to brokerapi.New, which returns an http.Handler that you can use to serve handle HTTP requests.

Alternatively, if you already have a *mux.Router that you want to attach service broker routes to, you can use brokerapi.AttachRoutes. Note in this case, the Basic Authentication and Originating Identity middleware will not be set up, so you will have to attach them manually if required.

Error types

brokerapi defines a handful of error types in service_broker.go for some common error cases that your service broker may encounter. Return these from your ServiceBroker methods where appropriate, and brokerapi will do the "right thing" (™), and give Cloud Foundry an appropriate status code, as per the Service Broker API specification.

Custom Errors

NewFailureResponse() allows you to return a custom error from any of the ServiceBroker interface methods which return an error. Within this you must define an error, a HTTP response status code and a logging key. You can also use the NewFailureResponseBuilder() to add a custom Error: value in the response, or indicate that the broker should return an empty response rather than the error message.

Originating Identity

The request context for every request contains the unparsed X-Broker-API-Originating-Identity header under the key originatingIdentityKey. More details on how the Open Service Broker API manages request originating identity is available here.

Example Service Broker

You can see the cf-redis service broker uses the BrokerAPI package to create a service broker for Redis.

Documentation

Index

Constants

View Source
const (
	PermissionRouteForwarding = RequiredPermission("route_forwarding")
	PermissionSyslogDrain     = RequiredPermission("syslog_drain")
	PermissionVolumeMount     = RequiredPermission("volume_mount")
)

Variables

View Source
var (
	ErrInstanceAlreadyExists = NewFailureResponseBuilder(
		errors.New(instanceExistsMsg), http.StatusConflict, instanceAlreadyExistsErrorKey,
	).WithEmptyResponse().Build()

	ErrInstanceDoesNotExist = NewFailureResponseBuilder(
		errors.New(instanceDoesntExistMsg), http.StatusGone, instanceMissingErrorKey,
	).WithEmptyResponse().Build()

	ErrInstanceLimitMet = NewFailureResponse(
		errors.New(serviceLimitReachedMsg), http.StatusInternalServerError, instanceLimitReachedErrorKey,
	)

	ErrBindingAlreadyExists = NewFailureResponse(
		errors.New(bindingExistsMsg), http.StatusConflict, bindingAlreadyExistsErrorKey,
	)

	ErrBindingDoesNotExist = NewFailureResponseBuilder(
		errors.New(bindingDoesntExistMsg), http.StatusGone, bindingMissingErrorKey,
	).WithEmptyResponse().Build()

	ErrBindingNotFound = NewFailureResponseBuilder(
		errors.New(bindingNotFoundMsg), http.StatusNotFound, bindingNotFoundErrorKey,
	).WithEmptyResponse().Build()

	ErrAsyncRequired = NewFailureResponseBuilder(
		errors.New(asyncRequiredMsg), http.StatusUnprocessableEntity, asyncRequiredKey,
	).WithErrorKey("AsyncRequired").Build()

	ErrPlanChangeNotSupported = NewFailureResponseBuilder(
		errors.New(planChangeUnsupportedMsg), http.StatusUnprocessableEntity, planChangeNotSupportedKey,
	).WithErrorKey("PlanChangeNotSupported").Build()

	ErrRawParamsInvalid = NewFailureResponse(
		errors.New(rawInvalidParamsMsg), http.StatusUnprocessableEntity, invalidRawParamsKey,
	)

	ErrAppGuidNotProvided = NewFailureResponse(
		errors.New(appGuidMissingMsg), http.StatusUnprocessableEntity, appGuidNotProvidedErrorKey,
	)

	ErrPlanQuotaExceeded    = errors.New(servicePlanQuotaExceededMsg)
	ErrServiceQuotaExceeded = errors.New(serviceQuotaExceededMsg)

	ErrConcurrentInstanceAccess = NewFailureResponseBuilder(
		errors.New(concurrentInstanceAccessMsg), http.StatusUnprocessableEntity, concurrentAccessKey,
	).WithErrorKey("ConcurrencyError")

	ErrMaintenanceInfoConflict = NewFailureResponseBuilder(
		errors.New(maintenanceInfoConflictMsg), http.StatusUnprocessableEntity, maintenanceInfoConflictKey,
	).WithErrorKey("MaintenanceInfoConflict").Build()

	ErrMaintenanceInfoNilConflict = NewFailureResponseBuilder(
		errors.New(maintenanceInfoNilConflictMsg), http.StatusUnprocessableEntity, maintenanceInfoConflictKey,
	).WithErrorKey("MaintenanceInfoConflict").Build()
)

Functions

func AttachRoutes

func AttachRoutes(router *mux.Router, serviceBroker ServiceBroker, logger lager.Logger)

func BindableValue

func BindableValue(v bool) *bool

func FreeValue

func FreeValue(v bool) *bool

func GetJsonNames

func GetJsonNames(s reflect.Value) (res []string)

func New

func New(serviceBroker ServiceBroker, logger lager.Logger, brokerCredentials BrokerCredentials) http.Handler

Types

type AsyncBindResponse

type AsyncBindResponse struct {
	OperationData string `json:"operation,omitempty"`
}

type BindDetails

type BindDetails struct {
	AppGUID       string          `json:"app_guid"`
	PlanID        string          `json:"plan_id"`
	ServiceID     string          `json:"service_id"`
	BindResource  *BindResource   `json:"bind_resource,omitempty"`
	RawContext    json.RawMessage `json:"context,omitempty"`
	RawParameters json.RawMessage `json:"parameters,omitempty"`
}

func (BindDetails) GetRawContext

func (d BindDetails) GetRawContext() json.RawMessage

func (BindDetails) GetRawParameters

func (d BindDetails) GetRawParameters() json.RawMessage

type BindResource

type BindResource struct {
	AppGuid            string `json:"app_guid,omitempty"`
	SpaceGuid          string `json:"space_guid,omitempty"`
	Route              string `json:"route,omitempty"`
	CredentialClientID string `json:"credential_client_id,omitempty"`
}

type Binding

type Binding struct {
	IsAsync         bool          `json:"is_async"`
	OperationData   string        `json:"operation_data"`
	Credentials     interface{}   `json:"credentials"`
	SyslogDrainURL  string        `json:"syslog_drain_url"`
	RouteServiceURL string        `json:"route_service_url"`
	VolumeMounts    []VolumeMount `json:"volume_mounts"`
}

type BindingResponse

type BindingResponse struct {
	Credentials     interface{}   `json:"credentials"`
	SyslogDrainURL  string        `json:"syslog_drain_url,omitempty"`
	RouteServiceURL string        `json:"route_service_url,omitempty"`
	VolumeMounts    []VolumeMount `json:"volume_mounts,omitempty"`
}

type BrokerCredentials

type BrokerCredentials struct {
	Username string
	Password string
}

type CatalogResponse

type CatalogResponse struct {
	Services []Service `json:"services"`
}

type DeprovisionDetails

type DeprovisionDetails struct {
	PlanID    string `json:"plan_id"`
	ServiceID string `json:"service_id"`
}

type DeprovisionResponse

type DeprovisionResponse struct {
	OperationData string `json:"operation,omitempty"`
}

type DeprovisionServiceSpec

type DeprovisionServiceSpec struct {
	IsAsync       bool
	OperationData string
}

type DetailsWithRawContext

type DetailsWithRawContext interface {
	GetRawContext() json.RawMessage
}

type DetailsWithRawParameters

type DetailsWithRawParameters interface {
	GetRawParameters() json.RawMessage
}

type EmptyResponse

type EmptyResponse struct{}

type ErrorResponse

type ErrorResponse struct {
	Error       string `json:"error,omitempty"`
	Description string `json:"description"`
}

type ExperimentalVolumeMount

type ExperimentalVolumeMount struct {
	ContainerPath string                         `json:"container_path"`
	Mode          string                         `json:"mode"`
	Private       ExperimentalVolumeMountPrivate `json:"private"`
}

type ExperimentalVolumeMountBindingResponse

type ExperimentalVolumeMountBindingResponse struct {
	Credentials     interface{}               `json:"credentials"`
	SyslogDrainURL  string                    `json:"syslog_drain_url,omitempty"`
	RouteServiceURL string                    `json:"route_service_url,omitempty"`
	VolumeMounts    []ExperimentalVolumeMount `json:"volume_mounts,omitempty"`
}

type ExperimentalVolumeMountPrivate

type ExperimentalVolumeMountPrivate struct {
	Driver  string `json:"driver"`
	GroupID string `json:"group_id"`
	Config  string `json:"config"`
}

type FailureResponse

type FailureResponse struct {
	// contains filtered or unexported fields
}

FailureResponse can be returned from any of the `ServiceBroker` interface methods which allow an error to be returned. Doing so will provide greater control over the HTTP response.

func NewFailureResponse

func NewFailureResponse(err error, statusCode int, loggerAction string) *FailureResponse

NewFailureResponse returns a pointer to a new instance of FailureResponse. err will by default be used as both a logging message and HTTP response description. statusCode is the HTTP status code to be returned, must be 4xx or 5xx loggerAction is a short description which will be used as the action if the error is logged.

func (*FailureResponse) AppendErrorMessage

func (f *FailureResponse) AppendErrorMessage(msg string) *FailureResponse

AppendErrorMessage returns an error with the message updated. All other properties are preserved.

func (*FailureResponse) ErrorResponse

func (f *FailureResponse) ErrorResponse() interface{}

ErrorResponse returns an interface{} which will be JSON encoded and form the body of the HTTP response

func (*FailureResponse) LoggerAction

func (f *FailureResponse) LoggerAction() string

LoggerAction returns the loggerAction, used as the action when logging

func (*FailureResponse) ValidatedStatusCode

func (f *FailureResponse) ValidatedStatusCode(logger lager.Logger) int

ValidatedStatusCode returns the HTTP response status code. If the code is not 4xx or 5xx, an InternalServerError will be returned instead.

type FailureResponseBuilder

type FailureResponseBuilder struct {
	// contains filtered or unexported fields
}

FailureResponseBuilder provides a fluent set of methods to build a *FailureResponse.

func NewFailureResponseBuilder

func NewFailureResponseBuilder(err error, statusCode int, loggerAction string) *FailureResponseBuilder

NewFailureResponseBuilder returns a pointer to a newly instantiated FailureResponseBuilder Accepts required arguments to create a FailureResponse.

func (*FailureResponseBuilder) Build

Build returns the generated FailureResponse built using previously configured variables.

func (*FailureResponseBuilder) WithEmptyResponse

func (f *FailureResponseBuilder) WithEmptyResponse() *FailureResponseBuilder

WithEmptyResponse will cause the built FailureResponse to return an empty JSON object as the HTTP response body

func (*FailureResponseBuilder) WithErrorKey

func (f *FailureResponseBuilder) WithErrorKey(errorKey string) *FailureResponseBuilder

WithErrorKey adds a custom ErrorKey which will be used in FailureResponse to add an `Error` field to the JSON HTTP response body

type GetBindingResponse

type GetBindingResponse struct {
	BindingResponse
	Parameters interface{} `json:"parameters,omitempty"`
}

type GetBindingSpec

type GetBindingSpec struct {
	Credentials     interface{}
	SyslogDrainURL  string
	RouteServiceURL string
	VolumeMounts    []VolumeMount
	Parameters      interface{}
}

type GetInstanceDetailsSpec

type GetInstanceDetailsSpec struct {
	ServiceID    string      `json:"service_id"`
	PlanID       string      `json:"plan_id"`
	DashboardURL string      `json:"dashboard_url"`
	Parameters   interface{} `json:"parameters"`
}

type GetInstanceResponse

type GetInstanceResponse struct {
	ServiceID    string      `json:"service_id"`
	PlanID       string      `json:"plan_id"`
	DashboardURL string      `json:"dashboard_url,omitempty"`
	Parameters   interface{} `json:"parameters,omitempty"`
}

type LastOperation

type LastOperation struct {
	State       LastOperationState
	Description string
}

type LastOperationResponse

type LastOperationResponse struct {
	State       LastOperationState `json:"state"`
	Description string             `json:"description,omitempty"`
}

type LastOperationState

type LastOperationState string
const (
	InProgress LastOperationState = "in progress"
	Succeeded  LastOperationState = "succeeded"
	Failed     LastOperationState = "failed"
)

type MaintenanceInfo

type MaintenanceInfo struct {
	Public  map[string]string `json:"public,omitempty"`
	Private string            `json:"private,omitempty"`
}

type PollDetails

type PollDetails struct {
	ServiceID     string `json:"service_id"`
	PlanID        string `json:"plan_id"`
	OperationData string `json:"operation"`
}

type PreviousValues

type PreviousValues struct {
	PlanID    string `json:"plan_id"`
	ServiceID string `json:"service_id"`
	OrgID     string `json:"organization_id"`
	SpaceID   string `json:"space_id"`
}

type ProvisionDetails

type ProvisionDetails struct {
	ServiceID        string          `json:"service_id"`
	PlanID           string          `json:"plan_id"`
	OrganizationGUID string          `json:"organization_guid"`
	SpaceGUID        string          `json:"space_guid"`
	RawContext       json.RawMessage `json:"context,omitempty"`
	RawParameters    json.RawMessage `json:"parameters,omitempty"`
	MaintenanceInfo  MaintenanceInfo `json:"maintenance_info,omitempty"`
}

func (ProvisionDetails) GetRawContext

func (d ProvisionDetails) GetRawContext() json.RawMessage

func (ProvisionDetails) GetRawParameters

func (d ProvisionDetails) GetRawParameters() json.RawMessage

type ProvisionedServiceSpec

type ProvisionedServiceSpec struct {
	IsAsync       bool
	DashboardURL  string
	OperationData string
}

type ProvisioningResponse

type ProvisioningResponse struct {
	DashboardURL  string `json:"dashboard_url,omitempty"`
	OperationData string `json:"operation,omitempty"`
}

type RequiredPermission

type RequiredPermission string

type Schema

type Schema struct {
	Parameters map[string]interface{} `json:"parameters"`
}

type Service

type Service struct {
	ID                   string                  `json:"id"`
	Name                 string                  `json:"name"`
	Description          string                  `json:"description"`
	Bindable             bool                    `json:"bindable"`
	InstancesRetrievable bool                    `json:"instances_retrievable,omitempty"`
	BindingsRetrievable  bool                    `json:"bindings_retrievable,omitempty"`
	Tags                 []string                `json:"tags,omitempty"`
	PlanUpdatable        bool                    `json:"plan_updateable"`
	Plans                []ServicePlan           `json:"plans"`
	Requires             []RequiredPermission    `json:"requires,omitempty"`
	Metadata             *ServiceMetadata        `json:"metadata,omitempty"`
	DashboardClient      *ServiceDashboardClient `json:"dashboard_client,omitempty"`
}

type ServiceBindingSchema

type ServiceBindingSchema struct {
	Create Schema `json:"create,omitempty"`
}

type ServiceBroker

type ServiceBroker interface {
	// Services gets the catalog of services offered by the service broker
	//   GET /v2/catalog
	Services(ctx context.Context) ([]Service, error)

	// Provision creates a new service instance
	//   PUT /v2/service_instances/{instance_id}
	Provision(ctx context.Context, instanceID string, details ProvisionDetails, asyncAllowed bool) (ProvisionedServiceSpec, error)

	// Deprovision deletes an existing service instance
	//  DELETE /v2/service_instances/{instance_id}
	Deprovision(ctx context.Context, instanceID string, details DeprovisionDetails, asyncAllowed bool) (DeprovisionServiceSpec, error)

	// GetInstance fetches information about a service instance
	//   GET /v2/service_instances/{instance_id}
	GetInstance(ctx context.Context, instanceID string) (GetInstanceDetailsSpec, error)

	// Update modifies an existing service instance
	//  PATCH /v2/service_instances/{instance_id}
	Update(ctx context.Context, instanceID string, details UpdateDetails, asyncAllowed bool) (UpdateServiceSpec, error)

	// LastOperation fetches last operation state for a service instance
	//   GET /v2/service_instances/{instance_id}/last_operation
	LastOperation(ctx context.Context, instanceID string, details PollDetails) (LastOperation, error)

	// Bind creates a new service binding
	//   PUT /v2/service_instances/{instance_id}/service_bindings/{binding_id}
	Bind(ctx context.Context, instanceID, bindingID string, details BindDetails, asyncAllowed bool) (Binding, error)

	// Unbind deletes an existing service binding
	//   DELETE /v2/service_instances/{instance_id}/service_bindings/{binding_id}
	Unbind(ctx context.Context, instanceID, bindingID string, details UnbindDetails, asyncAllowed bool) (UnbindSpec, error)

	// GetBinding fetches an existing service binding
	//   GET /v2/service_instances/{instance_id}/service_bindings/{binding_id}
	GetBinding(ctx context.Context, instanceID, bindingID string) (GetBindingSpec, error)

	// LastBindingOperation fetches last operation state for a service binding
	//   GET /v2/service_instances/{instance_id}/service_bindings/{binding_id}/last_operation
	LastBindingOperation(ctx context.Context, instanceID, bindingID string, details PollDetails) (LastOperation, error)
}

Each method of the ServiceBroker interface maps to an individual endpoint of the Open Service Broker API.

The specification is available here: https://github.com/openservicebrokerapi/servicebroker/blob/v2.14/spec.md

The OpenAPI documentation is available here: http://petstore.swagger.io/?url=https://raw.githubusercontent.com/openservicebrokerapi/servicebroker/v2.14/openapi.yaml

type ServiceDashboardClient

type ServiceDashboardClient struct {
	ID          string `json:"id"`
	Secret      string `json:"secret"`
	RedirectURI string `json:"redirect_uri"`
}

type ServiceInstanceSchema

type ServiceInstanceSchema struct {
	Create Schema `json:"create,omitempty"`
	Update Schema `json:"update,omitempty"`
}

type ServiceMetadata

type ServiceMetadata struct {
	DisplayName         string `json:"displayName,omitempty"`
	ImageUrl            string `json:"imageUrl,omitempty"`
	LongDescription     string `json:"longDescription,omitempty"`
	ProviderDisplayName string `json:"providerDisplayName,omitempty"`
	DocumentationUrl    string `json:"documentationUrl,omitempty"`
	SupportUrl          string `json:"supportUrl,omitempty"`
	Shareable           *bool  `json:"shareable,omitempty"`
	AdditionalMetadata  map[string]interface{}
}

func (ServiceMetadata) MarshalJSON

func (sm ServiceMetadata) MarshalJSON() ([]byte, error)

func (*ServiceMetadata) UnmarshalJSON

func (sm *ServiceMetadata) UnmarshalJSON(data []byte) error

type ServicePlan

type ServicePlan struct {
	ID              string               `json:"id"`
	Name            string               `json:"name"`
	Description     string               `json:"description"`
	Free            *bool                `json:"free,omitempty"`
	Bindable        *bool                `json:"bindable,omitempty"`
	Metadata        *ServicePlanMetadata `json:"metadata,omitempty"`
	Schemas         *ServiceSchemas      `json:"schemas,omitempty"`
	MaintenanceInfo *MaintenanceInfo     `json:"maintenance_info,omitempty"`
}

type ServicePlanCost

type ServicePlanCost struct {
	Amount map[string]float64 `json:"amount"`
	Unit   string             `json:"unit"`
}

type ServicePlanMetadata

type ServicePlanMetadata struct {
	DisplayName        string            `json:"displayName,omitempty"`
	Bullets            []string          `json:"bullets,omitempty"`
	Costs              []ServicePlanCost `json:"costs,omitempty"`
	AdditionalMetadata map[string]interface{}
}

func (ServicePlanMetadata) MarshalJSON

func (spm ServicePlanMetadata) MarshalJSON() ([]byte, error)

func (*ServicePlanMetadata) UnmarshalJSON

func (spm *ServicePlanMetadata) UnmarshalJSON(data []byte) error

type ServiceSchemas

type ServiceSchemas struct {
	Instance ServiceInstanceSchema `json:"service_instance,omitempty"`
	Binding  ServiceBindingSchema  `json:"service_binding,omitempty"`
}

type SharedDevice

type SharedDevice struct {
	VolumeId    string                 `json:"volume_id"`
	MountConfig map[string]interface{} `json:"mount_config"`
}

type UnbindDetails

type UnbindDetails struct {
	PlanID    string `json:"plan_id"`
	ServiceID string `json:"service_id"`
}

type UnbindResponse

type UnbindResponse struct {
	OperationData string `json:"operation,omitempty"`
}

type UnbindSpec

type UnbindSpec struct {
	IsAsync       bool
	OperationData string
}

type UpdateDetails

type UpdateDetails struct {
	ServiceID       string          `json:"service_id"`
	PlanID          string          `json:"plan_id"`
	RawParameters   json.RawMessage `json:"parameters,omitempty"`
	PreviousValues  PreviousValues  `json:"previous_values"`
	RawContext      json.RawMessage `json:"context,omitempty"`
	MaintenanceInfo MaintenanceInfo `json:"maintenance_info,omitempty"`
}

func (UpdateDetails) GetRawParameters

func (d UpdateDetails) GetRawParameters() json.RawMessage

type UpdateResponse

type UpdateResponse struct {
	DashboardURL  string `json:"dashboard_url,omitempty"`
	OperationData string `json:"operation,omitempty"`
}

type UpdateServiceSpec

type UpdateServiceSpec struct {
	IsAsync       bool
	DashboardURL  string
	OperationData string
}

type VolumeMount

type VolumeMount struct {
	Driver       string       `json:"driver"`
	ContainerDir string       `json:"container_dir"`
	Mode         string       `json:"mode"`
	DeviceType   string       `json:"device_type"`
	Device       SharedDevice `json:"device"`
}

Directories

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.
middlewares

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL