repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/toggles/toggle_test.go | pkg/toggles/toggle_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 toggles
import (
"fmt"
"github.com/spf13/viper"
)
func ExampleToggle_EnvironmentVariable() {
ts := NewToggleSet("foo.")
toggle := ts.Toggle("bar", true, "bar gets a default of true")
fmt.Println(toggle.EnvironmentVariable())
// Output: GSB_FOO_BAR
}
func ExampleToggle_IsActive() {
ts := NewToggleSet("foo.")
toggle := ts.Toggle("bar", true, "bar gets a default of true")
fmt.Println(toggle.IsActive())
viper.Set("foo.bar", "false")
defer viper.Reset()
fmt.Println(toggle.IsActive())
// Output: true
// false
}
func ExampleToggleSet_Toggles() {
ts := NewToggleSet("foo.")
// add some toggles
ts.Toggle("z", true, "a toggle")
ts.Toggle("a", false, "another toggle")
ts.Toggle("b", true, "a third toggle")
for _, tgl := range ts.Toggles() {
fmt.Printf("name: %s, var: %s, description: %q, default: %v\n", tgl.Name, tgl.EnvironmentVariable(), tgl.Description, tgl.Default)
}
// Output: name: a, var: GSB_FOO_A, description: "another toggle", default: false
// name: b, var: GSB_FOO_B, description: "a third toggle", default: true
// name: z, var: GSB_FOO_Z, description: "a toggle", default: true
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/registry.go | pkg/broker/registry.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"fmt"
"log"
"sort"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/toggles"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
)
var (
// The following flags enable and disable services based on their tags.
// The guiding philosophy for defaults is optimistic about new technology and pessimistic about old.
lifecycleTagToggles = map[string]toggles.Toggle{
"preview": toggles.Features.Toggle("enable-preview-services", true, `Enable services that are new to the broker this release.`),
"unmaintained": toggles.Features.Toggle("enable-unmaintained-services", false, `Enable broker services that are unmaintained.`),
"eol": toggles.Features.Toggle("enable-eol-services", false, `Enable broker services that are end of life.`),
"beta": toggles.Features.Toggle("enable-gcp-beta-services", true, "Enable services that are in GCP Beta. These have no SLA or support policy."),
"deprecated": toggles.Features.Toggle("enable-gcp-deprecated-services", false, "Enable services that use deprecated GCP components."),
"terraform": toggles.Features.Toggle("enable-terraform-services", false, "Enable services that use the experimental, unstable, Terraform back-end."),
}
enableBuiltinServices = toggles.Features.Toggle("enable-builtin-services", true, `Enable services that are built in to the broker i.e. not brokerpaks.`)
)
// BrokerRegistry holds the list of ServiceDefinitions that can be provisioned
// by the GCP Service Broker.
type BrokerRegistry map[string]*ServiceDefinition
// Registers a ServiceDefinition with the service registry that various commands
// poll to create the catalog, documentation, etc.
func (brokerRegistry BrokerRegistry) Register(service *ServiceDefinition) {
name := service.Name
if _, ok := brokerRegistry[name]; ok {
log.Fatalf("Tried to register multiple instances of: %q", name)
}
// Test deserializing the user defined plans and service definition
if _, err := service.CatalogEntry(); err != nil {
log.Fatalf("Error registering service %q, %s", name, err)
}
if err := service.Validate(); err != nil {
log.Fatalf("Error validating service %q, %s", name, err)
}
brokerRegistry[name] = service
}
// GetEnabledServices returns a list of all registered brokers that the user
// has enabled the use of.
func (brokerRegistry *BrokerRegistry) GetEnabledServices() ([]*ServiceDefinition, error) {
var out []*ServiceDefinition
for _, svc := range brokerRegistry.GetAllServices() {
isEnabled := true
if svc.IsBuiltin {
isEnabled = enableBuiltinServices.IsActive()
}
if entry, err := svc.CatalogEntry(); err != nil {
return nil, err
} else {
tags := utils.NewStringSet(entry.Tags...)
for tag, toggle := range lifecycleTagToggles {
if !toggle.IsActive() && tags.Contains(tag) {
isEnabled = false
break
}
}
}
if isEnabled {
out = append(out, svc)
}
}
return out, nil
}
// GetAllServices returns a list of all registered brokers whether or not the
// user has enabled them. The brokers are sorted in lexocographic order based
// on name.
func (brokerRegistry BrokerRegistry) GetAllServices() []*ServiceDefinition {
var out []*ServiceDefinition
for _, svc := range brokerRegistry {
out = append(out, svc)
}
// Sort by name so there's a consistent order in the UI and tests.
sort.Slice(out, func(i int, j int) bool { return out[i].Name < out[j].Name })
return out
}
// GetServiceById returns the service with the given ID, if it does not exist
// or one of the services has a parse error then an error is returned.
func (brokerRegistry BrokerRegistry) GetServiceById(id string) (*ServiceDefinition, error) {
for _, svc := range brokerRegistry {
if svc.Id == id {
return svc, nil
}
}
return nil, fmt.Errorf("Unknown service ID: %q", id)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/service_definition.go | pkg/broker/service_definition.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"encoding/json"
"fmt"
"os"
"strings"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/toggles"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"github.com/spf13/viper"
"golang.org/x/oauth2/jwt"
)
var enableCatalogSchemas = toggles.Features.Toggle("enable-catalog-schemas", false, `Enable generating JSONSchema for the service catalog.`)
// ServiceDefinition holds the necessary details to describe an OSB service and
// provision it.
type ServiceDefinition struct {
Id string
Name string
Description string
DisplayName string
ImageUrl string
DocumentationUrl string
SupportUrl string
Tags []string
Bindable bool
PlanUpdateable bool
Plans []ServicePlan
ProvisionInputVariables []BrokerVariable
ProvisionComputedVariables []varcontext.DefaultVariable
BindInputVariables []BrokerVariable
BindOutputVariables []BrokerVariable
BindComputedVariables []varcontext.DefaultVariable
PlanVariables []BrokerVariable
Examples []ServiceExample
DefaultRoleWhitelist []string
// ProviderBuilder creates a new provider given the project, auth, and logger.
ProviderBuilder func(projectId string, auth *jwt.Config, logger lager.Logger) ServiceProvider
// IsBuiltin is true if the service is built-in to the platform.
IsBuiltin bool
}
var _ validation.Validatable = (*ServiceDefinition)(nil)
// Validate implements validation.Validatable.
func (sd *ServiceDefinition) Validate() (errs *validation.FieldError) {
errs = errs.Also(
validation.ErrIfNotUUID(sd.Id, "Id"),
validation.ErrIfNotOSBName(sd.Name, "Name"),
)
if sd.ImageUrl != "" {
errs = errs.Also(validation.ErrIfNotURL(sd.ImageUrl, "ImageUrl"))
}
if sd.DocumentationUrl != "" {
errs = errs.Also(validation.ErrIfNotURL(sd.DocumentationUrl, "DocumentationUrl"))
}
if sd.SupportUrl != "" {
errs = errs.Also(validation.ErrIfNotURL(sd.SupportUrl, "SupportUrl"))
}
for i, v := range sd.ProvisionInputVariables {
errs = errs.Also(v.Validate().ViaFieldIndex("ProvisionInputVariables", i))
}
for i, v := range sd.ProvisionComputedVariables {
errs = errs.Also(v.Validate().ViaFieldIndex("ProvisionComputedVariables", i))
}
for i, v := range sd.BindInputVariables {
errs = errs.Also(v.Validate().ViaFieldIndex("BindInputVariables", i))
}
for i, v := range sd.BindOutputVariables {
errs = errs.Also(v.Validate().ViaFieldIndex("BindOutputVariables", i))
}
for i, v := range sd.BindComputedVariables {
errs = errs.Also(v.Validate().ViaFieldIndex("BindComputedVariables", i))
}
for i, v := range sd.PlanVariables {
errs = errs.Also(v.Validate().ViaFieldIndex("PlanVariables", i))
}
return errs
}
// UserDefinedPlansProperty computes the Viper property name for the JSON list
// of user-defined service plans.
func (svc *ServiceDefinition) UserDefinedPlansProperty() string {
return fmt.Sprintf("service.%s.plans", svc.Name)
}
// ProvisionDefaultOverrideProperty returns the Viper property name for the
// object users can set to override the default values on provision.
func (svc *ServiceDefinition) ProvisionDefaultOverrideProperty() string {
return fmt.Sprintf("service.%s.provision.defaults", svc.Name)
}
// ProvisionDefaultOverrides returns the deserialized JSON object for the
// operator-provided property overrides.
func (svc *ServiceDefinition) ProvisionDefaultOverrides() map[string]interface{} {
return viper.GetStringMap(svc.ProvisionDefaultOverrideProperty())
}
// IsRoleWhitelistEnabled returns false if the service has no default whitelist
// meaning it does not allow any roles.
func (svc *ServiceDefinition) IsRoleWhitelistEnabled() bool {
return len(svc.DefaultRoleWhitelist) > 0
}
// BindDefaultOverrideProperty returns the Viper property name for the
// object users can set to override the default values on bind.
func (svc *ServiceDefinition) BindDefaultOverrideProperty() string {
return fmt.Sprintf("service.%s.bind.defaults", svc.Name)
}
// BindDefaultOverrides returns the deserialized JSON object for the
// operator-provided property overrides.
func (svc *ServiceDefinition) BindDefaultOverrides() map[string]interface{} {
return viper.GetStringMap(svc.BindDefaultOverrideProperty())
}
// TileUserDefinedPlansVariable returns the name of the user defined plans
// variable for the broker tile.
func (svc *ServiceDefinition) TileUserDefinedPlansVariable() string {
v := utils.PropertyToEnvUnprefixed(svc.Name)
v = strings.TrimPrefix(v, "GOOGLE_")
return v + "_CUSTOM_PLANS"
}
// CatalogEntry returns the service broker catalog entry for this service, it
// has metadata about the service so operators and programmers know which
// service and plan will work best for their purposes.
func (svc *ServiceDefinition) CatalogEntry() (*Service, error) {
userPlans, err := svc.UserDefinedPlans()
if err != nil {
return nil, err
}
sd := &Service{
Service: brokerapi.Service{
ID: svc.Id,
Name: svc.Name,
Description: svc.Description,
Metadata: &brokerapi.ServiceMetadata{
DisplayName: svc.DisplayName,
LongDescription: svc.Description,
DocumentationUrl: svc.DocumentationUrl,
ImageUrl: svc.ImageUrl,
SupportUrl: svc.SupportUrl,
},
Tags: svc.Tags,
Bindable: svc.Bindable,
PlanUpdatable: svc.PlanUpdateable,
},
Plans: append(svc.Plans, userPlans...),
}
if enableCatalogSchemas.IsActive() {
for i, _ := range sd.Plans {
sd.Plans[i].Schemas = svc.createSchemas()
}
}
return sd, nil
}
// createSchemas creates JSONSchemas compatible with the OSB spec for provision and bind.
// It leaves the instance update schema empty to indicate updates are not supported.
func (svc *ServiceDefinition) createSchemas() *brokerapi.ServiceSchemas {
return &brokerapi.ServiceSchemas{
Instance: brokerapi.ServiceInstanceSchema{
Create: brokerapi.Schema{
Parameters: CreateJsonSchema(svc.ProvisionInputVariables),
},
},
Binding: brokerapi.ServiceBindingSchema{
Create: brokerapi.Schema{
Parameters: CreateJsonSchema(svc.BindInputVariables),
},
},
}
}
// GetPlanById finds a plan in this service by its UUID.
func (svc *ServiceDefinition) GetPlanById(planId string) (*ServicePlan, error) {
catalogEntry, err := svc.CatalogEntry()
if err != nil {
return nil, err
}
for _, plan := range catalogEntry.Plans {
if plan.ID == planId {
return &plan, nil
}
}
return nil, fmt.Errorf("Plan ID %q could not be found", planId)
}
// UserDefinedPlans extracts user defined plans from the environment, failing if
// the plans were not valid JSON or were missing required properties/variables.
func (svc *ServiceDefinition) UserDefinedPlans() ([]ServicePlan, error) {
// There's a mismatch between how plans are used internally and defined by
// the user and the tile. In the environment variables we parse an array of
// flat maps, but internally extra variables need to be put into a sub-map.
// e.g. they come in as [{"id":"1234", "name":"foo", "A": 1, "B": 2}]
// but we need [{"id":"1234", "name":"foo", "service_properties":{"A": 1, "B": 2}}]
// Go doesn't support this natively so we do it manually here.
rawPlans := []json.RawMessage{}
// Unmarshal the plans from the viper configuration which is just a JSON list
// of plans
if userPlanJSON := viper.GetString(svc.UserDefinedPlansProperty()); userPlanJSON != "" {
if err := json.Unmarshal([]byte(userPlanJSON), &rawPlans); err != nil {
return []ServicePlan{}, err
}
}
// Unmarshal tile plans if they're included, which are a JSON object where
// keys are
if tilePlans := os.Getenv(svc.TileUserDefinedPlansVariable()); tilePlans != "" {
var rawTilePlans map[string]json.RawMessage
if err := json.Unmarshal([]byte(tilePlans), &rawTilePlans); err != nil {
return []ServicePlan{}, err
}
for _, v := range rawTilePlans {
rawPlans = append(rawPlans, v)
}
}
plans := []ServicePlan{}
for _, rawPlan := range rawPlans {
plan := ServicePlan{}
remainder, err := utils.UnmarshalObjectRemainder(rawPlan, &plan)
if err != nil {
return []ServicePlan{}, err
}
plan.ServiceProperties = make(map[string]string)
if err := json.Unmarshal(remainder, &plan.ServiceProperties); err != nil {
return []ServicePlan{}, err
}
// reading from a tile we need to move their GUID to an ID field
if plan.ID == "" {
plan.ID = plan.ServiceProperties["guid"]
}
if err := svc.validatePlan(plan); err != nil {
return []ServicePlan{}, err
}
plans = append(plans, plan)
}
return plans, nil
}
func (svc *ServiceDefinition) validatePlan(plan ServicePlan) error {
if plan.ID == "" {
return fmt.Errorf("%s custom plan %+v is missing an id", svc.Name, plan)
}
if plan.Name == "" {
return fmt.Errorf("%s custom plan %+v is missing a name", svc.Name, plan)
}
if svc.PlanVariables == nil {
return nil
}
for _, customVar := range svc.PlanVariables {
if !customVar.Required {
continue
}
if _, ok := plan.ServiceProperties[customVar.FieldName]; !ok {
return fmt.Errorf("%s custom plan %+v is missing required property %s", svc.Name, plan, customVar.FieldName)
}
}
return nil
}
func (svc *ServiceDefinition) provisionDefaults() []varcontext.DefaultVariable {
var out []varcontext.DefaultVariable
for _, provisionVar := range svc.ProvisionInputVariables {
out = append(out, varcontext.DefaultVariable{Name: provisionVar.FieldName, Default: provisionVar.Default, Overwrite: false, Type: string(provisionVar.Type)})
}
return out
}
func (svc *ServiceDefinition) bindDefaults() []varcontext.DefaultVariable {
var out []varcontext.DefaultVariable
for _, v := range svc.BindInputVariables {
out = append(out, varcontext.DefaultVariable{Name: v.FieldName, Default: v.Default, Overwrite: false, Type: string(v.Type)})
}
return out
}
// ProvisionVariables gets the variable resolution context for a provision request.
// Variables have a very specific resolution order, and this function populates the context to preserve that.
// The variable resolution order is the following:
//
// 1. Variables defined in your `computed_variables` JSON list.
// 2. Variables defined by the selected service plan in its `service_properties` map.
// 3. Variables overridden in the plan's `provision_overrides` map.
// 4. User defined variables (in `provision_input_variables` or `bind_input_variables`)
// 5. Operator default variables loaded from the environment.
// 6. Default variables (in `provision_input_variables` or `bind_input_variables`).
//
// Loading into the map occurs slightly differently.
// Default variables and computed_variables get executed by interpolation.
// User defined varaibles are not to prevent side-channel attacks.
// Default variables may reference user provided variables.
// For example, to create a default database name based on a user-provided instance name.
// Therefore, they get executed conditionally if a user-provided variable does not exist.
// Computed variables get executed either unconditionally or conditionally for greater flexibility.
func (svc *ServiceDefinition) ProvisionVariables(instanceId string, details brokerapi.ProvisionDetails, plan ServicePlan) (*varcontext.VarContext, error) {
// The namespaces of these values roughly align with the OSB spec.
constants := map[string]interface{}{
"request.plan_id": details.PlanID,
"request.service_id": details.ServiceID,
"request.instance_id": instanceId,
"request.default_labels": utils.ExtractDefaultLabels(instanceId, details),
}
builder := varcontext.Builder().
SetEvalConstants(constants).
MergeMap(svc.ProvisionDefaultOverrides()).
MergeJsonObject(details.GetRawParameters()).
MergeMap(plan.ProvisionOverrides).
MergeDefaults(svc.provisionDefaults()).
MergeMap(plan.GetServiceProperties()).
MergeDefaults(svc.ProvisionComputedVariables)
return buildAndValidate(builder, svc.ProvisionInputVariables)
}
// BindVariables gets the variable resolution context for a bind request.
// Variables have a very specific resolution order, and this function populates the context to preserve that.
// The variable resolution order is the following:
//
// 1. Variables defined in your `computed_variables` JSON list.
// 2. Variables overridden in the plan's `bind_overrides` map.
// 3. User defined variables (in `bind_input_variables`)
// 4. Operator default variables loaded from the environment.
// 5. Default variables (in `bind_input_variables`).
//
func (svc *ServiceDefinition) BindVariables(instance models.ServiceInstanceDetails, bindingID string, details brokerapi.BindDetails, plan *ServicePlan) (*varcontext.VarContext, error) {
otherDetails := make(map[string]interface{})
if err := instance.GetOtherDetails(&otherDetails); err != nil {
return nil, err
}
appGuid := ""
if details.BindResource != nil {
appGuid = details.BindResource.AppGuid
}
// The namespaces of these values roughly align with the OSB spec.
constants := map[string]interface{}{
// specified in the URL
"request.binding_id": bindingID,
"request.instance_id": instance.ID,
// specified in the request body
// Note: the value in instance is considered the official record so values
// are pulled from there rather than the request. In a future version of OSB
// the duplicate sending of fields is likely to be removed.
"request.plan_id": instance.PlanId,
"request.service_id": instance.ServiceId,
"request.app_guid": appGuid,
"request.plan_properties": plan.GetServiceProperties(),
// specified by the existing instance
"instance.name": instance.Name,
"instance.details": otherDetails,
}
builder := varcontext.Builder().
SetEvalConstants(constants).
MergeMap(svc.BindDefaultOverrides()).
MergeJsonObject(details.GetRawParameters()).
MergeMap(plan.BindOverrides).
MergeDefaults(svc.bindDefaults()).
MergeDefaults(svc.BindComputedVariables)
return buildAndValidate(builder, svc.BindInputVariables)
}
// buildAndValidate builds the varcontext and if it's valid validates the
// resulting context against the JSONSchema defined by the BrokerVariables
// exactly one of VarContext and error will be nil upon return.
func buildAndValidate(builder *varcontext.ContextBuilder, vars []BrokerVariable) (*varcontext.VarContext, error) {
vc, err := builder.Build()
if err != nil {
return nil, err
}
if err := ValidateVariables(vc.ToMap(), vars); err != nil {
return nil, err
}
return vc, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/example.go | pkg/broker/example.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
// ServiceExample holds example configurations for a service that _should_
// work.
type ServiceExample struct {
// Name is a human-readable name of the example.
Name string `json:"name" yaml:"name"`
// Description is a long-form description of what this example is about.
Description string `json:"description" yaml:"description"`
// PlanId is the plan this example will run against.
PlanId string `json:"plan_id" yaml:"plan_id"`
// ProvisionParams is the JSON object that will be passed to provision.
ProvisionParams map[string]interface{} `json:"provision_params" yaml:"provision_params"`
// BindParams is the JSON object that will be passed to bind. If nil,
// this example DOES NOT include a bind portion.
BindParams map[string]interface{} `json:"bind_params" yaml:"bind_params"`
}
var _ validation.Validatable = (*ServiceExample)(nil)
// Validate implements validation.Validatable.
func (action *ServiceExample) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(action.Name, "name"),
validation.ErrIfBlank(action.Description, "description"),
validation.ErrIfBlank(action.PlanId, "plan_id"),
)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/catalog.go | pkg/broker/catalog.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"github.com/pivotal-cf/brokerapi"
)
// Service overrides the canonical Service Broker service type using a custom
// type for Plans, everything else is the same.
type Service struct {
brokerapi.Service
Plans []ServicePlan `json:"plans"`
}
// ToPlain converts this service to a plain PCF Service definition.
func (s Service) ToPlain() brokerapi.Service {
plain := s.Service
plainPlans := []brokerapi.ServicePlan{}
for _, plan := range s.Plans {
plainPlans = append(plainPlans, plan.ServicePlan)
}
plain.Plans = plainPlans
return plain
}
// ServicePlan extends the OSB ServicePlan by including a map of key/value
// pairs that can be used to pass additional information to the back-end.
type ServicePlan struct {
brokerapi.ServicePlan
ServiceProperties map[string]string `json:"service_properties"`
ProvisionOverrides map[string]interface{} `json:"provision_overrides,omitempty"`
BindOverrides map[string]interface{} `json:"bind_overrides,omitempty"`
}
// GetServiceProperties gets the plan settings variables as a string->interface map.
func (sp *ServicePlan) GetServiceProperties() map[string]interface{} {
props := make(map[string]interface{})
for k, v := range sp.ServiceProperties {
props[k] = v
}
return props
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/variables.go | pkg/broker/variables.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"fmt"
"sort"
"strings"
"unicode"
"errors"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext/interpolation"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/hashicorp/go-multierror"
"github.com/xeipuuv/gojsonschema"
)
const (
JsonTypeString JsonType = "string"
JsonTypeNumeric JsonType = "number"
JsonTypeInteger JsonType = "integer"
JsonTypeBoolean JsonType = "boolean"
)
type JsonType string
type BrokerVariable struct {
// Is this variable required?
Required bool `yaml:"required,omitempty"`
// The name of the JSON field this variable serializes/deserializes to
FieldName string `yaml:"field_name"`
// The JSONSchema type of the field
Type JsonType `yaml:"type"`
// Human readable info about the field.
Details string `yaml:"details"`
// The default value of the field.
Default interface{} `yaml:"default,omitempty"`
// If there are a limited number of valid values for this field then
// Enum will hold them in value:friendly name pairs
Enum map[interface{}]string `yaml:"enum,omitempty"`
// Constraints holds JSON Schema validations defined for this variable.
// Keys are valid JSON Schema validation keywords, and values are their
// associated values.
// http://json-schema.org/latest/json-schema-validation.html
Constraints map[string]interface{} `yaml:"constraints,omitempty"`
}
var _ validation.Validatable = (*ServiceDefinition)(nil)
// Validate implements validation.Validatable.
func (bv *BrokerVariable) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(bv.FieldName, "field_name"),
validation.ErrIfNotJSONSchemaType(string(bv.Type), "type"),
validation.ErrIfBlank(bv.Details, "details"),
)
}
// ToSchema converts the BrokerVariable into the value part of a JSON Schema.
func (bv *BrokerVariable) ToSchema() map[string]interface{} {
schema := map[string]interface{}{}
// Setting the auto-generated title comes first so it can be overridden
// manually by constraints in special cases.
if bv.FieldName != "" {
schema[validation.KeyTitle] = fieldNameToLabel(bv.FieldName)
}
for k, v := range bv.Constraints {
schema[k] = v
}
if len(bv.Enum) > 0 {
enumeration := []interface{}{}
for k, _ := range bv.Enum {
enumeration = append(enumeration, k)
}
// Sort enumerations lexocographically for documentation consistency.
sort.Slice(enumeration, func(i int, j int) bool {
return fmt.Sprintf("%v", enumeration[i]) < fmt.Sprintf("%v", enumeration[j])
})
schema[validation.KeyEnum] = enumeration
}
if bv.Details != "" {
schema[validation.KeyDescription] = bv.Details
}
if bv.Type != "" {
schema[validation.KeyType] = bv.Type
}
if bv.Default != nil {
// HIL values shouldn't get set as Defaults, instead they should be added to the description field.
if defaultString, ok := bv.Default.(string); ok && interpolation.IsHILExpression(defaultString) {
genDesc := fmt.Sprintf("%s If you do not specify this field, it will be generated by the template %q", bv.Details, defaultString)
schema[validation.KeyDescription] = strings.TrimSpace(genDesc)
} else {
schema[validation.KeyDefault] = bv.Default
}
}
return schema
}
func fieldNameToLabel(fieldName string) string {
acronyms := map[string]string{
"id": "ID",
"uri": "URI",
"url": "URL",
"gb": "GB",
"jdbc": "JDBC",
}
components := strings.FieldsFunc(fieldName, func(c rune) bool {
return unicode.IsSpace(c) || c == '-' || c == '_' || c == '.'
})
for i, c := range components {
if replace, ok := acronyms[c]; ok {
components[i] = replace
} else {
components[i] = strings.ToUpper(c[:1]) + c[1:]
}
}
return strings.Join(components, " ")
}
// Apply defaults adds default values for missing broker variables.
func ApplyDefaults(parameters map[string]interface{}, variables []BrokerVariable) {
for _, v := range variables {
if _, ok := parameters[v.FieldName]; !ok && v.Default != nil {
parameters[v.FieldName] = v.Default
}
}
}
func ValidateVariables(parameters map[string]interface{}, variables []BrokerVariable) error {
schema := CreateJsonSchema(variables)
return ValidateVariablesAgainstSchema(parameters, schema)
}
// ValidateVariables validates a list of BrokerVariables are adhering to their JSONSchema.
func ValidateVariablesAgainstSchema(parameters map[string]interface{}, schema map[string]interface{}) error {
result, err := gojsonschema.Validate(gojsonschema.NewGoLoader(schema), gojsonschema.NewGoLoader(parameters))
if err != nil {
return err
}
resultErrors := result.Errors()
if len(resultErrors) == 0 {
return nil
}
allErrors := &multierror.Error{
ErrorFormat: utils.SingleLineErrorFormatter,
}
for _, r := range resultErrors {
multierror.Append(allErrors, errors.New(r.String()))
}
return allErrors
}
// CreateJsonSchema outputs a JSONSchema given a list of BrokerVariables
func CreateJsonSchema(schemaVariables []BrokerVariable) map[string]interface{} {
required := utils.NewStringSet()
properties := make(map[string]interface{})
for _, variable := range schemaVariables {
properties[variable.FieldName] = variable.ToSchema()
if variable.Required {
required.Add(variable.FieldName)
}
}
schema := map[string]interface{}{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": properties,
}
if !required.IsEmpty() {
schema["required"] = required.ToSlice()
}
return schema
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/service_provider.go | pkg/broker/service_provider.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
//go:generate counterfeiter . ServiceProvider
// ServiceProvider performs the actual provisoning/deprovisioning part of a service broker request.
// The broker will handle storing state and validating inputs while a ServiceProvider changes GCP to match the desired state.
// ServiceProviders are expected to interact with the state of the system entirely through their inputs and outputs.
// Specifically, they MUST NOT modify any general state of the broker in the database.
type ServiceProvider interface {
// Provision creates the necessary resources that an instance of this service
// needs to operate.
Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error)
// Bind provisions the necessary resources for a user to be able to connect to the provisioned service.
// This may include creating service accounts, granting permissions, and adding users to services e.g. a SQL database user.
// It stores information necessary to access the service _and_ delete the binding in the returned map.
Bind(ctx context.Context, vc *varcontext.VarContext) (map[string]interface{}, error)
// BuildInstanceCredentials combines the bindRecord with any additional
// info from the instance to create credentials for the binding.
BuildInstanceCredentials(ctx context.Context, bindRecord models.ServiceBindingCredentials, instance models.ServiceInstanceDetails) (*brokerapi.Binding, error)
// Unbind deprovisions the resources created with Bind.
Unbind(ctx context.Context, instance models.ServiceInstanceDetails, details models.ServiceBindingCredentials) error
// Deprovision deprovisions the service.
// If the deprovision is asynchronous (results in a long-running job), then operationId is returned.
// If no error and no operationId are returned, then the deprovision is expected to have been completed successfully.
Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (operationId *string, err error)
PollInstance(ctx context.Context, instance models.ServiceInstanceDetails) (bool, error)
ProvisionsAsync() bool
DeprovisionsAsync() bool
// UpdateInstanceDetails updates the ServiceInstanceDetails with the most recent state from GCP.
// This function is optional, but will be called after async provisions, updates, and possibly
// on broker version changes.
// Return a nil error if you choose not to implement this function.
UpdateInstanceDetails(ctx context.Context, instance *models.ServiceInstanceDetails) error
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/variables_test.go | pkg/broker/variables_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"errors"
"reflect"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
func TestBrokerVariable_ToSchema(t *testing.T) {
cases := map[string]struct {
BrokerVar BrokerVariable
Expected map[string]interface{}
}{
"blank": {
BrokerVariable{}, map[string]interface{}{},
},
"enums get copied": {
BrokerVariable{Enum: map[interface{}]string{"a": "description", "b": "description"}},
map[string]interface{}{
"enum": []interface{}{"a", "b"},
},
},
"details are copied": {
BrokerVariable{Details: "more information"},
map[string]interface{}{
"description": "more information",
},
},
"type is copied": {
BrokerVariable{Type: JsonTypeString},
map[string]interface{}{
"type": JsonTypeString,
},
},
"default is copied": {
BrokerVariable{Default: "some-value"},
map[string]interface{}{
"default": "some-value",
},
},
"template defaults": {
BrokerVariable{Default: "${33}", Details: "Some value."},
map[string]interface{}{
"description": `Some value. If you do not specify this field, it will be generated by the template "${33}"`,
},
},
"full test": {
BrokerVariable{
FieldName: "full_test_field_name",
Default: "some-value",
Type: JsonTypeString,
Details: "more information",
Enum: map[interface{}]string{"b": "description", "a": "description"},
Constraints: map[string]interface{}{
"examples": []string{"SAMPLEA", "SAMPLEB"},
},
},
map[string]interface{}{
"title": "Full Test Field Name",
"default": "some-value",
"type": JsonTypeString,
"description": "more information",
"enum": []interface{}{"a", "b"},
"examples": []string{"SAMPLEA", "SAMPLEB"},
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := tc.BrokerVar.ToSchema()
if !reflect.DeepEqual(actual, tc.Expected) {
t.Errorf("Expected ToSchema to be: %v, got: %v", tc.Expected, actual)
}
})
}
}
func TestBrokerVariable_ValidateVariables(t *testing.T) {
cases := map[string]struct {
Parameters map[string]interface{}
Variables []BrokerVariable
Expected error
}{
"nil params": {
Parameters: nil,
Variables: nil,
Expected: errors.New("1 error(s) occurred: (root): Invalid type. Expected: object, given: null"),
},
"nil vars check": {
Parameters: map[string]interface{}{},
Variables: nil,
Expected: nil,
},
"integer": {
Parameters: map[string]interface{}{
"test": 12,
},
Variables: []BrokerVariable{
{
Required: true,
FieldName: "test",
Type: JsonTypeInteger,
},
},
Expected: nil,
},
"unexpected type": {
Parameters: map[string]interface{}{
"test": "didn't see that coming",
},
Variables: []BrokerVariable{
{
Required: true,
FieldName: "test",
Type: JsonTypeInteger,
},
},
Expected: errors.New("1 error(s) occurred: test: Invalid type. Expected: integer, given: string"),
},
"test constraints": {
Parameters: map[string]interface{}{
"test": 0,
},
Variables: []BrokerVariable{
{
Required: true,
FieldName: "test",
Type: JsonTypeInteger,
Constraints: validation.NewConstraintBuilder().
Minimum(10).
Build(),
},
},
Expected: errors.New("1 error(s) occurred: test: Must be greater than or equal to 10"),
},
"test enum": {
Parameters: map[string]interface{}{
"test": "not this one",
},
Variables: []BrokerVariable{
{
Required: true,
FieldName: "test",
Type: JsonTypeString,
Enum: map[interface{}]string{
"one": "it's either this one",
"theother": "or this one",
},
},
},
Expected: errors.New("1 error(s) occurred: test: test must be one of the following: \"one\", \"theother\""),
},
"test missing": {
Parameters: map[string]interface{}{},
Variables: []BrokerVariable{
{
Required: true,
FieldName: "test",
Type: JsonTypeString,
Enum: map[interface{}]string{
"one": "it's either this one",
"theother": "or this one",
},
},
},
Expected: errors.New("1 error(s) occurred: test: test is required"),
},
"test incorrect schema": {
Parameters: map[string]interface{}{},
Variables: []BrokerVariable{
{
Type: "garbage",
},
},
Expected: errors.New("has a primitive type that is NOT VALID -- given: /garbage/ Expected valid values are:[array boolean integer number null object string]"),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := ValidateVariables(tc.Parameters, tc.Variables)
if tc.Expected == nil {
if actual != nil {
t.Fatalf("Expected ValidateVariables not to raise an error but got %v", actual)
}
} else {
if actual == nil {
t.Fatalf("Expected ValidateVariables to be: %q, got: %v", tc.Expected.Error(), actual)
}
if actual.Error() != tc.Expected.Error() {
t.Errorf("Expected ValidateVariables error to be: %q, got: %q", tc.Expected.Error(), actual.Error())
}
}
})
}
}
func TestBrokerVariable_ApplyDefaults(t *testing.T) {
cases := map[string]struct {
Parameters map[string]interface{}
Variables []BrokerVariable
Expected map[string]interface{}
}{
"nil check": {
Parameters: nil,
Variables: nil,
Expected: nil,
},
"simple": {
Parameters: map[string]interface{}{},
Variables: []BrokerVariable{
{
FieldName: "test",
Type: JsonTypeInteger,
Default: 123,
},
},
Expected: map[string]interface{}{
"test": 123,
},
},
"do not replace": {
Parameters: map[string]interface{}{
"test": 123,
},
Variables: []BrokerVariable{
{
FieldName: "test",
Type: JsonTypeInteger,
Default: 456,
},
},
Expected: map[string]interface{}{
"test": 123,
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
ApplyDefaults(tc.Parameters, tc.Variables)
if !reflect.DeepEqual(tc.Parameters, tc.Expected) {
t.Errorf("Expected ValidateVariables to be: %v, got: %v", tc.Expected, tc.Parameters)
}
})
}
}
func TestFieldNameToLabel(t *testing.T) {
cases := map[string]struct {
Field string
Expected string
}{
"snake_case": {Field: "my_field", Expected: "My Field"},
"kebab-case": {Field: "kebab-case", Expected: "Kebab Case"},
"dot.notation": {Field: "dot.notation", Expected: "Dot Notation"},
"uri": {Field: "my_uri", Expected: "My URI"},
"url": {Field: "my_url", Expected: "My URL"},
"id": {Field: "my_id", Expected: "My ID"},
"gb": {Field: "size_gb", Expected: "Size GB"},
"jdbc": {Field: "jdbc", Expected: "JDBC"},
"double_separator": {Field: "my__id", Expected: "My ID"},
"single_char": {Field: "a b c", Expected: "A B C"},
"blank": {Field: "", Expected: ""},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
field := fieldNameToLabel(tc.Field)
if field != tc.Expected {
t.Errorf("Expected: %q got %q", tc.Expected, field)
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/broker_test.go | pkg/broker/broker_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"testing"
"os"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"github.com/spf13/viper"
)
func ExampleServiceDefinition_UserDefinedPlansProperty() {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
}
fmt.Println(service.UserDefinedPlansProperty())
// Output: service.left-handed-smoke-sifter.plans
}
func ExampleServiceDefinition_IsRoleWhitelistEnabled() {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
DefaultRoleWhitelist: []string{"a", "b", "c"},
}
fmt.Println(service.IsRoleWhitelistEnabled())
service.DefaultRoleWhitelist = nil
fmt.Println(service.IsRoleWhitelistEnabled())
// Output: true
// false
}
func ExampleServiceDefinition_TileUserDefinedPlansVariable() {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "google-spanner",
}
fmt.Println(service.TileUserDefinedPlansVariable())
// Output: SPANNER_CUSTOM_PLANS
}
func ExampleServiceDefinition_GetPlanById() {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
Plans: []ServicePlan{
{ServicePlan: brokerapi.ServicePlan{ID: "builtin-plan", Name: "Builtin!"}},
},
}
viper.Set(service.UserDefinedPlansProperty(), `[{"id":"custom-plan", "name": "Custom!"}]`)
defer viper.Reset()
plan, err := service.GetPlanById("builtin-plan")
fmt.Printf("builtin-plan: %q %v\n", plan.Name, err)
plan, err = service.GetPlanById("custom-plan")
fmt.Printf("custom-plan: %q %v\n", plan.Name, err)
_, err = service.GetPlanById("missing-plan")
fmt.Printf("missing-plan: %s\n", err)
// Output: builtin-plan: "Builtin!" <nil>
// custom-plan: "Custom!" <nil>
// missing-plan: Plan ID "missing-plan" could not be found
}
func TestServiceDefinition_UserDefinedPlans(t *testing.T) {
cases := map[string]struct {
Value interface{}
TileValue string
PlanIds map[string]bool
ExpectError bool
}{
"default-no-plans": {
Value: nil,
PlanIds: map[string]bool{},
ExpectError: false,
},
"single-plan": {
Value: `[{"id":"aaa","name":"aaa","instances":"3"}]`,
PlanIds: map[string]bool{"aaa": true},
ExpectError: false,
},
"bad-json": {
Value: `42`,
PlanIds: map[string]bool{},
ExpectError: true,
},
"multiple-plans": {
Value: `[{"id":"aaa","name":"aaa","instances":"3"},{"id":"bbb","name":"bbb","instances":"3"}]`,
PlanIds: map[string]bool{"aaa": true, "bbb": true},
ExpectError: false,
},
"missing-name": {
Value: `[{"id":"aaa","instances":"3"}]`,
PlanIds: map[string]bool{},
ExpectError: true,
},
"missing-id": {
Value: `[{"name":"aaa","instances":"3"}]`,
PlanIds: map[string]bool{},
ExpectError: true,
},
"missing-instances": {
Value: `[{"name":"aaa","id":"aaa"}]`,
PlanIds: map[string]bool{},
ExpectError: true,
},
"tile environment variable": {
TileValue: `{
"plan-100":{
"description":"plan-100",
"display_name":"plan-100",
"guid":"495bf186-e1c2-4c7e-abc1-84b1a8634858",
"instances":"100",
"name":"plan-100",
"service":"4bc59b9a-8520-409f-85da-1c7552315863"
},
"custom-plan2":{
"description":"test",
"display_name":"asdf",
"guid":"938cfc91-bca3-4f9d-b384-1e4ad6f965ce",
"instances":"10",
"name":"custom-plan2",
"service":"4bc59b9a-8520-409f-85da-1c7552315863"
}
}`,
PlanIds: map[string]bool{
"495bf186-e1c2-4c7e-abc1-84b1a8634858": true,
"938cfc91-bca3-4f9d-b384-1e4ad6f965ce": true,
},
ExpectError: false,
},
}
service := ServiceDefinition{
Id: "abcd-efgh-ijkl",
Name: "left-handed-smoke-sifter",
PlanVariables: []BrokerVariable{
{
Required: true,
FieldName: "instances",
Type: JsonTypeString,
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
os.Setenv(service.TileUserDefinedPlansVariable(), tc.TileValue)
defer os.Unsetenv(service.TileUserDefinedPlansVariable())
viper.Set(service.UserDefinedPlansProperty(), tc.Value)
defer viper.Reset()
plans, err := service.UserDefinedPlans()
// Check errors
hasErr := err != nil
if hasErr != tc.ExpectError {
t.Fatalf("Expected Error? %v, got error: %v", tc.ExpectError, err)
}
// Check IDs
if len(plans) != len(tc.PlanIds) {
t.Errorf("Expected %d plans, but got %d (%v)", len(tc.PlanIds), len(plans), plans)
}
for _, plan := range plans {
if _, ok := tc.PlanIds[plan.ID]; !ok {
t.Errorf("Got unexpected plan id %s, expected %+v", plan.ID, tc.PlanIds)
}
}
})
}
}
func TestServiceDefinition_CatalogEntry(t *testing.T) {
cases := map[string]struct {
UserPlans interface{}
PlanIds map[string]bool
ExpectError bool
}{
"no-customization": {
UserPlans: nil,
PlanIds: map[string]bool{},
ExpectError: false,
},
"custom-plans": {
UserPlans: `[{"id":"aaa","name":"aaa"},{"id":"bbb","name":"bbb"}]`,
PlanIds: map[string]bool{"aaa": true, "bbb": true},
ExpectError: false,
},
"bad-plan-json": {
UserPlans: `333`,
PlanIds: map[string]bool{},
ExpectError: true,
},
}
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
viper.Set(service.UserDefinedPlansProperty(), tc.UserPlans)
defer viper.Reset()
srvc, err := service.CatalogEntry()
hasErr := err != nil
if hasErr != tc.ExpectError {
t.Errorf("Expected Error? %v, got error: %v", tc.ExpectError, err)
}
if err == nil && len(srvc.Plans) != len(tc.PlanIds) {
t.Errorf("Expected %d plans, but got %d (%+v)", len(tc.PlanIds), len(srvc.Plans), srvc.Plans)
for _, plan := range srvc.Plans {
if _, ok := tc.PlanIds[plan.ID]; !ok {
t.Errorf("Got unexpected plan id %s, expected %+v", plan.ID, tc.PlanIds)
}
}
}
})
}
}
func ExampleServiceDefinition_CatalogEntry() {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
Plans: []ServicePlan{
{ServicePlan: brokerapi.ServicePlan{ID: "builtin-plan", Name: "Builtin!"}},
},
ProvisionInputVariables: []BrokerVariable{
{FieldName: "location", Type: JsonTypeString, Default: "us"},
},
BindInputVariables: []BrokerVariable{
{FieldName: "name", Type: JsonTypeString, Default: "name"},
},
}
srvc, err := service.CatalogEntry()
if err != nil {
panic(err)
}
// Schemas should be nil by default
fmt.Println("schemas with flag off:", srvc.ToPlain().Plans[0].Schemas)
viper.Set("compatibility.enable-catalog-schemas", true)
defer viper.Reset()
srvc, err = service.CatalogEntry()
if err != nil {
panic(err)
}
eq := reflect.DeepEqual(srvc.ToPlain().Plans[0].Schemas, service.createSchemas())
fmt.Println("schema was generated?", eq)
// Output: schemas with flag off: <nil>
// schema was generated? true
}
func TestServiceDefinition_ProvisionVariables(t *testing.T) {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
Plans: []ServicePlan{
{ServicePlan: brokerapi.ServicePlan{ID: "builtin-plan", Name: "Builtin!"}},
},
ProvisionInputVariables: []BrokerVariable{
{
FieldName: "location",
Type: JsonTypeString,
Default: "us",
},
{
FieldName: "name",
Type: JsonTypeString,
Default: "name-${location}",
Constraints: validation.NewConstraintBuilder().
MaxLength(30).
Build(),
},
},
ProvisionComputedVariables: []varcontext.DefaultVariable{
{
Name: "location",
Default: "${str.truncate(10, location)}",
Overwrite: true,
},
{
Name: "maybe-missing",
Default: "default",
Overwrite: false,
},
},
}
cases := map[string]struct {
UserParams string
ServiceProperties map[string]string
DefaultOverride string
ProvisionOverrides map[string]interface{}
ExpectedError error
ExpectedContext map[string]interface{}
}{
"empty": {
UserParams: "",
ServiceProperties: map[string]string{},
ExpectedContext: map[string]interface{}{
"location": "us",
"name": "name-us",
"maybe-missing": "default",
},
},
"service has missing param": {
UserParams: "",
ServiceProperties: map[string]string{"maybe-missing": "custom"},
ExpectedContext: map[string]interface{}{
"location": "us",
"name": "name-us",
"maybe-missing": "custom",
},
},
"location gets truncated": {
UserParams: `{"location": "averylonglocation"}`,
ServiceProperties: map[string]string{},
ExpectedContext: map[string]interface{}{
"location": "averylongl",
"name": "name-averylonglocation",
"maybe-missing": "default",
},
},
"user location and name": {
UserParams: `{"location": "eu", "name":"foo"}`,
ServiceProperties: map[string]string{},
ExpectedContext: map[string]interface{}{
"location": "eu",
"name": "foo",
"maybe-missing": "default",
},
},
"user tries to overwrite service var": {
UserParams: `{"location": "eu", "name":"foo", "service-provided":"test"}`,
ServiceProperties: map[string]string{"service-provided": "custom"},
ExpectedContext: map[string]interface{}{
"location": "eu",
"name": "foo",
"maybe-missing": "default",
"service-provided": "custom",
},
},
"operator defaults override computed defaults": {
UserParams: "",
DefaultOverride: `{"location":"eu"}`,
ServiceProperties: map[string]string{},
ExpectedContext: map[string]interface{}{
"location": "eu",
"name": "name-eu",
"maybe-missing": "default",
},
},
"user values override operator defaults": {
UserParams: `{"location":"nz"}`,
DefaultOverride: `{"location":"eu"}`,
ServiceProperties: map[string]string{},
ExpectedContext: map[string]interface{}{
"location": "nz",
"name": "name-nz",
"maybe-missing": "default",
},
},
"operator defaults are not evaluated": {
UserParams: `{"location":"us"}`,
DefaultOverride: `{"name":"foo-${location}"}`,
ServiceProperties: map[string]string{},
ExpectedContext: map[string]interface{}{
"location": "us",
"name": "foo-${location}",
"maybe-missing": "default",
},
},
"invalid-request": {
UserParams: `{"name":"some-name-that-is-longer-than-thirty-characters"}`,
ExpectedError: errors.New("1 error(s) occurred: name: String length must be less than or equal to 30"),
},
"provision_overrides override user params but not computed defaults": {
UserParams: `{"location":"us"}`,
DefaultOverride: "{}",
ServiceProperties: map[string]string{},
ProvisionOverrides: map[string]interface{}{"location": "eu"},
ExpectedContext: map[string]interface{}{
"location": "eu",
"name": "name-eu",
"maybe-missing": "default",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
viper.Set(service.ProvisionDefaultOverrideProperty(), tc.DefaultOverride)
defer viper.Reset()
details := brokerapi.ProvisionDetails{RawParameters: json.RawMessage(tc.UserParams)}
plan := ServicePlan{ServiceProperties: tc.ServiceProperties, ProvisionOverrides: tc.ProvisionOverrides}
vars, err := service.ProvisionVariables("instance-id-here", details, plan)
expectError(t, tc.ExpectedError, err)
if tc.ExpectedError == nil && !reflect.DeepEqual(vars.ToMap(), tc.ExpectedContext) {
t.Errorf("Expected context: %v got %v", tc.ExpectedContext, vars.ToMap())
}
})
}
}
func TestServiceDefinition_BindVariables(t *testing.T) {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
Plans: []ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "builtin-plan",
Name: "Builtin!",
},
ServiceProperties: map[string]string{
"service-property": "operator-set",
},
},
},
BindInputVariables: []BrokerVariable{
{
FieldName: "location",
Type: JsonTypeString,
Default: "us",
},
{
FieldName: "name",
Type: JsonTypeString,
Default: "name-${location}",
Constraints: validation.NewConstraintBuilder().
MaxLength(30).
Build(),
},
},
BindComputedVariables: []varcontext.DefaultVariable{
{
Name: "location",
Default: "${str.truncate(10, location)}",
Overwrite: true,
},
{
Name: "instance-foo",
Default: `${instance.details["foo"]}`,
Overwrite: true,
},
{
Name: "service-prop",
Default: `${request.plan_properties["service-property"]}`,
Overwrite: true,
},
},
}
cases := map[string]struct {
UserParams string
DefaultOverride string
BindOverrides map[string]interface{}
ExpectedError error
ExpectedContext map[string]interface{}
InstanceVars string
}{
"empty": {
UserParams: "",
InstanceVars: `{"foo":""}`,
ExpectedContext: map[string]interface{}{
"location": "us",
"name": "name-us",
"instance-foo": "",
"service-prop": "operator-set",
},
},
"location gets truncated": {
UserParams: `{"location": "averylonglocation"}`,
InstanceVars: `{"foo":"default"}`,
ExpectedContext: map[string]interface{}{
"location": "averylongl",
"name": "name-averylonglocation",
"instance-foo": "default",
"service-prop": "operator-set",
},
},
"user location and name": {
UserParams: `{"location": "eu", "name":"foo"}`,
InstanceVars: `{"foo":"default"}`,
ExpectedContext: map[string]interface{}{
"location": "eu",
"name": "foo",
"instance-foo": "default",
"service-prop": "operator-set",
},
},
"operator defaults override computed defaults": {
UserParams: "",
InstanceVars: `{"foo":"default"}`,
DefaultOverride: `{"location":"eu"}`,
ExpectedContext: map[string]interface{}{
"location": "eu",
"name": "name-eu",
"instance-foo": "default",
"service-prop": "operator-set",
},
},
"user values override operator defaults": {
UserParams: `{"location":"nz"}`,
InstanceVars: `{"foo":"default"}`,
DefaultOverride: `{"location":"eu"}`,
ExpectedContext: map[string]interface{}{
"location": "nz",
"name": "name-nz",
"instance-foo": "default",
"service-prop": "operator-set",
},
},
"operator defaults are not evaluated": {
UserParams: `{"location":"us"}`,
InstanceVars: `{"foo":"default"}`,
DefaultOverride: `{"name":"foo-${location}"}`,
ExpectedContext: map[string]interface{}{
"location": "us",
"name": "foo-${location}",
"instance-foo": "default",
"service-prop": "operator-set",
},
},
"instance info can get parsed": {
UserParams: `{"location":"us"}`,
InstanceVars: `{"foo":"bar"}`,
ExpectedContext: map[string]interface{}{
"location": "us",
"name": "name-us",
"instance-foo": "bar",
"service-prop": "operator-set",
},
},
"invalid-request": {
UserParams: `{"name":"some-name-that-is-longer-than-thirty-characters"}`,
InstanceVars: `{"foo":""}`,
ExpectedError: errors.New("1 error(s) occurred: name: String length must be less than or equal to 30"),
},
"bind_overrides override user params but not computed defaults": {
UserParams: `{"location":"us"}`,
InstanceVars: `{"foo":"default"}`,
BindOverrides: map[string]interface{}{"location": "eu"},
ExpectedContext: map[string]interface{}{
"location": "eu",
"name": "name-eu",
"instance-foo": "default",
"service-prop": "operator-set",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
viper.Set(service.BindDefaultOverrideProperty(), tc.DefaultOverride)
defer viper.Reset()
details := brokerapi.BindDetails{RawParameters: json.RawMessage(tc.UserParams)}
instance := models.ServiceInstanceDetails{OtherDetails: tc.InstanceVars}
service.Plans[0].BindOverrides = tc.BindOverrides
vars, err := service.BindVariables(instance, "binding-id-here", details, &service.Plans[0])
expectError(t, tc.ExpectedError, err)
if tc.ExpectedError == nil && !reflect.DeepEqual(vars.ToMap(), tc.ExpectedContext) {
t.Errorf("Expected context: %v got %v", tc.ExpectedContext, vars.ToMap())
}
})
}
}
func TestServiceDefinition_createSchemas(t *testing.T) {
service := ServiceDefinition{
Id: "00000000-0000-0000-0000-000000000000",
Name: "left-handed-smoke-sifter",
Plans: []ServicePlan{
{ServicePlan: brokerapi.ServicePlan{ID: "builtin-plan", Name: "Builtin!"}},
},
ProvisionInputVariables: []BrokerVariable{
{FieldName: "location", Type: JsonTypeString, Default: "us"},
},
BindInputVariables: []BrokerVariable{
{FieldName: "name", Type: JsonTypeString, Default: "name"},
},
}
schemas := service.createSchemas()
if schemas == nil {
t.Fatal("Schemas was nil, expected non-nil value")
}
// it populates the instance create schema with the fields in ProvisionInputVariables
instanceCreate := schemas.Instance.Create
if instanceCreate.Parameters == nil {
t.Error("instance create params were nil, expected a schema")
}
expectedCreateParams := CreateJsonSchema(service.ProvisionInputVariables)
if !reflect.DeepEqual(instanceCreate.Parameters, expectedCreateParams) {
t.Errorf("expected create params to be: %v got %v", expectedCreateParams, instanceCreate.Parameters)
}
// It leaves the instance update schema blank.
instanceUpdate := schemas.Instance.Update
if instanceUpdate.Parameters != nil {
t.Error("instance update params were not nil, expected nil")
}
// it populates the binding create schema with the fields in BindInputVariables.
bindCreate := schemas.Binding.Create
if bindCreate.Parameters == nil {
t.Error("bind create params were not nil, expected a schema")
}
expectedBindCreateParams := CreateJsonSchema(service.BindInputVariables)
if !reflect.DeepEqual(bindCreate.Parameters, expectedBindCreateParams) {
t.Errorf("expected create params to be: %v got %v", expectedBindCreateParams, bindCreate.Parameters)
}
}
func expectError(t *testing.T, expected, actual error) {
t.Helper()
expectedErr := expected != nil
gotErr := actual != nil
switch {
case expectedErr && gotErr:
if expected.Error() != actual.Error() {
t.Fatalf("Expected: %v, got: %v", expected, actual)
}
case expectedErr && !gotErr:
t.Fatalf("Expected: %v, got: %v", expected, actual)
case !expectedErr && gotErr:
t.Fatalf("Expected no error but got: %v", actual)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/registry_test.go | pkg/broker/registry_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 broker
import (
"testing"
"github.com/pivotal-cf/brokerapi"
"github.com/spf13/viper"
)
func TestRegistry_GetEnabledServices(t *testing.T) {
cases := map[string]struct {
Tag string
Property string
}{
"preview": {
Tag: "preview",
Property: "compatibility.enable-preview-services",
},
"unmaintained": {
Tag: "unmaintained",
Property: "compatibility.enable-unmaintained-services",
},
"eol": {
Tag: "eol",
Property: "compatibility.enable-eol-services",
},
"beta": {
Tag: "beta",
Property: "compatibility.enable-gcp-beta-services",
},
"deprecated": {
Tag: "deprecated",
Property: "compatibility.enable-gcp-deprecated-services",
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
defer viper.Reset()
sd := ServiceDefinition{
Id: "b9e4332e-b42b-4680-bda5-ea1506797474",
Name: "test-service",
Tags: []string{"gcp", tc.Tag},
Plans: []ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "e1d11f65-da66-46ad-977c-6d56513baf43",
Name: "Builtin!",
Description: "Standard storage class",
},
},
},
IsBuiltin: true,
}
registry := BrokerRegistry{}
registry.Register(&sd)
// shouldn't show up when property is false even if builtins are enabled
viper.Set("compatibility.enable-builtin-services", true)
viper.Set(tc.Property, false)
if defns, err := registry.GetEnabledServices(); err != nil {
t.Fatal(err)
} else if len(defns) != 0 {
t.Fatalf("Expected 0 definitions with %s disabled, but got %d", tc.Property, len(defns))
}
// should show up when property is true
viper.Set(tc.Property, true)
if defns, err := registry.GetEnabledServices(); err != nil {
t.Fatal(err)
} else if len(defns) != 1 {
t.Fatalf("Expected 1 definition with %s enabled, but got %d", tc.Property, len(defns))
}
// should not show up if the service is explicitly disabled
viper.Set("compatibility.enable-builtin-services", false)
if defns, err := registry.GetEnabledServices(); err != nil {
t.Fatal(err)
} else if len(defns) != 0 {
t.Fatalf("Expected no definition with builtins disabled, but got %d", len(defns))
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/brokerfakes/fake_service_provider.go | pkg/broker/brokerfakes/fake_service_provider.go | // Code generated by counterfeiter. DO NOT EDIT.
package brokerfakes
import (
context "context"
sync "sync"
models "github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
broker "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
varcontext "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
brokerapi "github.com/pivotal-cf/brokerapi"
)
type FakeServiceProvider struct {
BindStub func(context.Context, *varcontext.VarContext) (map[string]interface{}, error)
bindMutex sync.RWMutex
bindArgsForCall []struct {
arg1 context.Context
arg2 *varcontext.VarContext
}
bindReturns struct {
result1 map[string]interface{}
result2 error
}
bindReturnsOnCall map[int]struct {
result1 map[string]interface{}
result2 error
}
BuildInstanceCredentialsStub func(context.Context, models.ServiceBindingCredentials, models.ServiceInstanceDetails) (*brokerapi.Binding, error)
buildInstanceCredentialsMutex sync.RWMutex
buildInstanceCredentialsArgsForCall []struct {
arg1 context.Context
arg2 models.ServiceBindingCredentials
arg3 models.ServiceInstanceDetails
}
buildInstanceCredentialsReturns struct {
result1 *brokerapi.Binding
result2 error
}
buildInstanceCredentialsReturnsOnCall map[int]struct {
result1 *brokerapi.Binding
result2 error
}
DeprovisionStub func(context.Context, models.ServiceInstanceDetails, brokerapi.DeprovisionDetails) (*string, error)
deprovisionMutex sync.RWMutex
deprovisionArgsForCall []struct {
arg1 context.Context
arg2 models.ServiceInstanceDetails
arg3 brokerapi.DeprovisionDetails
}
deprovisionReturns struct {
result1 *string
result2 error
}
deprovisionReturnsOnCall map[int]struct {
result1 *string
result2 error
}
DeprovisionsAsyncStub func() bool
deprovisionsAsyncMutex sync.RWMutex
deprovisionsAsyncArgsForCall []struct {
}
deprovisionsAsyncReturns struct {
result1 bool
}
deprovisionsAsyncReturnsOnCall map[int]struct {
result1 bool
}
PollInstanceStub func(context.Context, models.ServiceInstanceDetails) (bool, error)
pollInstanceMutex sync.RWMutex
pollInstanceArgsForCall []struct {
arg1 context.Context
arg2 models.ServiceInstanceDetails
}
pollInstanceReturns struct {
result1 bool
result2 error
}
pollInstanceReturnsOnCall map[int]struct {
result1 bool
result2 error
}
ProvisionStub func(context.Context, *varcontext.VarContext) (models.ServiceInstanceDetails, error)
provisionMutex sync.RWMutex
provisionArgsForCall []struct {
arg1 context.Context
arg2 *varcontext.VarContext
}
provisionReturns struct {
result1 models.ServiceInstanceDetails
result2 error
}
provisionReturnsOnCall map[int]struct {
result1 models.ServiceInstanceDetails
result2 error
}
ProvisionsAsyncStub func() bool
provisionsAsyncMutex sync.RWMutex
provisionsAsyncArgsForCall []struct {
}
provisionsAsyncReturns struct {
result1 bool
}
provisionsAsyncReturnsOnCall map[int]struct {
result1 bool
}
UnbindStub func(context.Context, models.ServiceInstanceDetails, models.ServiceBindingCredentials) error
unbindMutex sync.RWMutex
unbindArgsForCall []struct {
arg1 context.Context
arg2 models.ServiceInstanceDetails
arg3 models.ServiceBindingCredentials
}
unbindReturns struct {
result1 error
}
unbindReturnsOnCall map[int]struct {
result1 error
}
UpdateInstanceDetailsStub func(context.Context, *models.ServiceInstanceDetails) error
updateInstanceDetailsMutex sync.RWMutex
updateInstanceDetailsArgsForCall []struct {
arg1 context.Context
arg2 *models.ServiceInstanceDetails
}
updateInstanceDetailsReturns struct {
result1 error
}
updateInstanceDetailsReturnsOnCall map[int]struct {
result1 error
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeServiceProvider) Bind(arg1 context.Context, arg2 *varcontext.VarContext) (map[string]interface{}, error) {
fake.bindMutex.Lock()
ret, specificReturn := fake.bindReturnsOnCall[len(fake.bindArgsForCall)]
fake.bindArgsForCall = append(fake.bindArgsForCall, struct {
arg1 context.Context
arg2 *varcontext.VarContext
}{arg1, arg2})
fake.recordInvocation("Bind", []interface{}{arg1, arg2})
fake.bindMutex.Unlock()
if fake.BindStub != nil {
return fake.BindStub(arg1, arg2)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.bindReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceProvider) BindCallCount() int {
fake.bindMutex.RLock()
defer fake.bindMutex.RUnlock()
return len(fake.bindArgsForCall)
}
func (fake *FakeServiceProvider) BindCalls(stub func(context.Context, *varcontext.VarContext) (map[string]interface{}, error)) {
fake.bindMutex.Lock()
defer fake.bindMutex.Unlock()
fake.BindStub = stub
}
func (fake *FakeServiceProvider) BindArgsForCall(i int) (context.Context, *varcontext.VarContext) {
fake.bindMutex.RLock()
defer fake.bindMutex.RUnlock()
argsForCall := fake.bindArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeServiceProvider) BindReturns(result1 map[string]interface{}, result2 error) {
fake.bindMutex.Lock()
defer fake.bindMutex.Unlock()
fake.BindStub = nil
fake.bindReturns = struct {
result1 map[string]interface{}
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) BindReturnsOnCall(i int, result1 map[string]interface{}, result2 error) {
fake.bindMutex.Lock()
defer fake.bindMutex.Unlock()
fake.BindStub = nil
if fake.bindReturnsOnCall == nil {
fake.bindReturnsOnCall = make(map[int]struct {
result1 map[string]interface{}
result2 error
})
}
fake.bindReturnsOnCall[i] = struct {
result1 map[string]interface{}
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) BuildInstanceCredentials(arg1 context.Context, arg2 models.ServiceBindingCredentials, arg3 models.ServiceInstanceDetails) (*brokerapi.Binding, error) {
fake.buildInstanceCredentialsMutex.Lock()
ret, specificReturn := fake.buildInstanceCredentialsReturnsOnCall[len(fake.buildInstanceCredentialsArgsForCall)]
fake.buildInstanceCredentialsArgsForCall = append(fake.buildInstanceCredentialsArgsForCall, struct {
arg1 context.Context
arg2 models.ServiceBindingCredentials
arg3 models.ServiceInstanceDetails
}{arg1, arg2, arg3})
fake.recordInvocation("BuildInstanceCredentials", []interface{}{arg1, arg2, arg3})
fake.buildInstanceCredentialsMutex.Unlock()
if fake.BuildInstanceCredentialsStub != nil {
return fake.BuildInstanceCredentialsStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.buildInstanceCredentialsReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceProvider) BuildInstanceCredentialsCallCount() int {
fake.buildInstanceCredentialsMutex.RLock()
defer fake.buildInstanceCredentialsMutex.RUnlock()
return len(fake.buildInstanceCredentialsArgsForCall)
}
func (fake *FakeServiceProvider) BuildInstanceCredentialsCalls(stub func(context.Context, models.ServiceBindingCredentials, models.ServiceInstanceDetails) (*brokerapi.Binding, error)) {
fake.buildInstanceCredentialsMutex.Lock()
defer fake.buildInstanceCredentialsMutex.Unlock()
fake.BuildInstanceCredentialsStub = stub
}
func (fake *FakeServiceProvider) BuildInstanceCredentialsArgsForCall(i int) (context.Context, models.ServiceBindingCredentials, models.ServiceInstanceDetails) {
fake.buildInstanceCredentialsMutex.RLock()
defer fake.buildInstanceCredentialsMutex.RUnlock()
argsForCall := fake.buildInstanceCredentialsArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeServiceProvider) BuildInstanceCredentialsReturns(result1 *brokerapi.Binding, result2 error) {
fake.buildInstanceCredentialsMutex.Lock()
defer fake.buildInstanceCredentialsMutex.Unlock()
fake.BuildInstanceCredentialsStub = nil
fake.buildInstanceCredentialsReturns = struct {
result1 *brokerapi.Binding
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) BuildInstanceCredentialsReturnsOnCall(i int, result1 *brokerapi.Binding, result2 error) {
fake.buildInstanceCredentialsMutex.Lock()
defer fake.buildInstanceCredentialsMutex.Unlock()
fake.BuildInstanceCredentialsStub = nil
if fake.buildInstanceCredentialsReturnsOnCall == nil {
fake.buildInstanceCredentialsReturnsOnCall = make(map[int]struct {
result1 *brokerapi.Binding
result2 error
})
}
fake.buildInstanceCredentialsReturnsOnCall[i] = struct {
result1 *brokerapi.Binding
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) Deprovision(arg1 context.Context, arg2 models.ServiceInstanceDetails, arg3 brokerapi.DeprovisionDetails) (*string, error) {
fake.deprovisionMutex.Lock()
ret, specificReturn := fake.deprovisionReturnsOnCall[len(fake.deprovisionArgsForCall)]
fake.deprovisionArgsForCall = append(fake.deprovisionArgsForCall, struct {
arg1 context.Context
arg2 models.ServiceInstanceDetails
arg3 brokerapi.DeprovisionDetails
}{arg1, arg2, arg3})
fake.recordInvocation("Deprovision", []interface{}{arg1, arg2, arg3})
fake.deprovisionMutex.Unlock()
if fake.DeprovisionStub != nil {
return fake.DeprovisionStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.deprovisionReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceProvider) DeprovisionCallCount() int {
fake.deprovisionMutex.RLock()
defer fake.deprovisionMutex.RUnlock()
return len(fake.deprovisionArgsForCall)
}
func (fake *FakeServiceProvider) DeprovisionCalls(stub func(context.Context, models.ServiceInstanceDetails, brokerapi.DeprovisionDetails) (*string, error)) {
fake.deprovisionMutex.Lock()
defer fake.deprovisionMutex.Unlock()
fake.DeprovisionStub = stub
}
func (fake *FakeServiceProvider) DeprovisionArgsForCall(i int) (context.Context, models.ServiceInstanceDetails, brokerapi.DeprovisionDetails) {
fake.deprovisionMutex.RLock()
defer fake.deprovisionMutex.RUnlock()
argsForCall := fake.deprovisionArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeServiceProvider) DeprovisionReturns(result1 *string, result2 error) {
fake.deprovisionMutex.Lock()
defer fake.deprovisionMutex.Unlock()
fake.DeprovisionStub = nil
fake.deprovisionReturns = struct {
result1 *string
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) DeprovisionReturnsOnCall(i int, result1 *string, result2 error) {
fake.deprovisionMutex.Lock()
defer fake.deprovisionMutex.Unlock()
fake.DeprovisionStub = nil
if fake.deprovisionReturnsOnCall == nil {
fake.deprovisionReturnsOnCall = make(map[int]struct {
result1 *string
result2 error
})
}
fake.deprovisionReturnsOnCall[i] = struct {
result1 *string
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) DeprovisionsAsync() bool {
fake.deprovisionsAsyncMutex.Lock()
ret, specificReturn := fake.deprovisionsAsyncReturnsOnCall[len(fake.deprovisionsAsyncArgsForCall)]
fake.deprovisionsAsyncArgsForCall = append(fake.deprovisionsAsyncArgsForCall, struct {
}{})
fake.recordInvocation("DeprovisionsAsync", []interface{}{})
fake.deprovisionsAsyncMutex.Unlock()
if fake.DeprovisionsAsyncStub != nil {
return fake.DeprovisionsAsyncStub()
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.deprovisionsAsyncReturns
return fakeReturns.result1
}
func (fake *FakeServiceProvider) DeprovisionsAsyncCallCount() int {
fake.deprovisionsAsyncMutex.RLock()
defer fake.deprovisionsAsyncMutex.RUnlock()
return len(fake.deprovisionsAsyncArgsForCall)
}
func (fake *FakeServiceProvider) DeprovisionsAsyncCalls(stub func() bool) {
fake.deprovisionsAsyncMutex.Lock()
defer fake.deprovisionsAsyncMutex.Unlock()
fake.DeprovisionsAsyncStub = stub
}
func (fake *FakeServiceProvider) DeprovisionsAsyncReturns(result1 bool) {
fake.deprovisionsAsyncMutex.Lock()
defer fake.deprovisionsAsyncMutex.Unlock()
fake.DeprovisionsAsyncStub = nil
fake.deprovisionsAsyncReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeServiceProvider) DeprovisionsAsyncReturnsOnCall(i int, result1 bool) {
fake.deprovisionsAsyncMutex.Lock()
defer fake.deprovisionsAsyncMutex.Unlock()
fake.DeprovisionsAsyncStub = nil
if fake.deprovisionsAsyncReturnsOnCall == nil {
fake.deprovisionsAsyncReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.deprovisionsAsyncReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeServiceProvider) PollInstance(arg1 context.Context, arg2 models.ServiceInstanceDetails) (bool, error) {
fake.pollInstanceMutex.Lock()
ret, specificReturn := fake.pollInstanceReturnsOnCall[len(fake.pollInstanceArgsForCall)]
fake.pollInstanceArgsForCall = append(fake.pollInstanceArgsForCall, struct {
arg1 context.Context
arg2 models.ServiceInstanceDetails
}{arg1, arg2})
fake.recordInvocation("PollInstance", []interface{}{arg1, arg2})
fake.pollInstanceMutex.Unlock()
if fake.PollInstanceStub != nil {
return fake.PollInstanceStub(arg1, arg2)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.pollInstanceReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceProvider) PollInstanceCallCount() int {
fake.pollInstanceMutex.RLock()
defer fake.pollInstanceMutex.RUnlock()
return len(fake.pollInstanceArgsForCall)
}
func (fake *FakeServiceProvider) PollInstanceCalls(stub func(context.Context, models.ServiceInstanceDetails) (bool, error)) {
fake.pollInstanceMutex.Lock()
defer fake.pollInstanceMutex.Unlock()
fake.PollInstanceStub = stub
}
func (fake *FakeServiceProvider) PollInstanceArgsForCall(i int) (context.Context, models.ServiceInstanceDetails) {
fake.pollInstanceMutex.RLock()
defer fake.pollInstanceMutex.RUnlock()
argsForCall := fake.pollInstanceArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeServiceProvider) PollInstanceReturns(result1 bool, result2 error) {
fake.pollInstanceMutex.Lock()
defer fake.pollInstanceMutex.Unlock()
fake.PollInstanceStub = nil
fake.pollInstanceReturns = struct {
result1 bool
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) PollInstanceReturnsOnCall(i int, result1 bool, result2 error) {
fake.pollInstanceMutex.Lock()
defer fake.pollInstanceMutex.Unlock()
fake.PollInstanceStub = nil
if fake.pollInstanceReturnsOnCall == nil {
fake.pollInstanceReturnsOnCall = make(map[int]struct {
result1 bool
result2 error
})
}
fake.pollInstanceReturnsOnCall[i] = struct {
result1 bool
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) Provision(arg1 context.Context, arg2 *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
fake.provisionMutex.Lock()
ret, specificReturn := fake.provisionReturnsOnCall[len(fake.provisionArgsForCall)]
fake.provisionArgsForCall = append(fake.provisionArgsForCall, struct {
arg1 context.Context
arg2 *varcontext.VarContext
}{arg1, arg2})
fake.recordInvocation("Provision", []interface{}{arg1, arg2})
fake.provisionMutex.Unlock()
if fake.ProvisionStub != nil {
return fake.ProvisionStub(arg1, arg2)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.provisionReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceProvider) ProvisionCallCount() int {
fake.provisionMutex.RLock()
defer fake.provisionMutex.RUnlock()
return len(fake.provisionArgsForCall)
}
func (fake *FakeServiceProvider) ProvisionCalls(stub func(context.Context, *varcontext.VarContext) (models.ServiceInstanceDetails, error)) {
fake.provisionMutex.Lock()
defer fake.provisionMutex.Unlock()
fake.ProvisionStub = stub
}
func (fake *FakeServiceProvider) ProvisionArgsForCall(i int) (context.Context, *varcontext.VarContext) {
fake.provisionMutex.RLock()
defer fake.provisionMutex.RUnlock()
argsForCall := fake.provisionArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeServiceProvider) ProvisionReturns(result1 models.ServiceInstanceDetails, result2 error) {
fake.provisionMutex.Lock()
defer fake.provisionMutex.Unlock()
fake.ProvisionStub = nil
fake.provisionReturns = struct {
result1 models.ServiceInstanceDetails
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) ProvisionReturnsOnCall(i int, result1 models.ServiceInstanceDetails, result2 error) {
fake.provisionMutex.Lock()
defer fake.provisionMutex.Unlock()
fake.ProvisionStub = nil
if fake.provisionReturnsOnCall == nil {
fake.provisionReturnsOnCall = make(map[int]struct {
result1 models.ServiceInstanceDetails
result2 error
})
}
fake.provisionReturnsOnCall[i] = struct {
result1 models.ServiceInstanceDetails
result2 error
}{result1, result2}
}
func (fake *FakeServiceProvider) ProvisionsAsync() bool {
fake.provisionsAsyncMutex.Lock()
ret, specificReturn := fake.provisionsAsyncReturnsOnCall[len(fake.provisionsAsyncArgsForCall)]
fake.provisionsAsyncArgsForCall = append(fake.provisionsAsyncArgsForCall, struct {
}{})
fake.recordInvocation("ProvisionsAsync", []interface{}{})
fake.provisionsAsyncMutex.Unlock()
if fake.ProvisionsAsyncStub != nil {
return fake.ProvisionsAsyncStub()
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.provisionsAsyncReturns
return fakeReturns.result1
}
func (fake *FakeServiceProvider) ProvisionsAsyncCallCount() int {
fake.provisionsAsyncMutex.RLock()
defer fake.provisionsAsyncMutex.RUnlock()
return len(fake.provisionsAsyncArgsForCall)
}
func (fake *FakeServiceProvider) ProvisionsAsyncCalls(stub func() bool) {
fake.provisionsAsyncMutex.Lock()
defer fake.provisionsAsyncMutex.Unlock()
fake.ProvisionsAsyncStub = stub
}
func (fake *FakeServiceProvider) ProvisionsAsyncReturns(result1 bool) {
fake.provisionsAsyncMutex.Lock()
defer fake.provisionsAsyncMutex.Unlock()
fake.ProvisionsAsyncStub = nil
fake.provisionsAsyncReturns = struct {
result1 bool
}{result1}
}
func (fake *FakeServiceProvider) ProvisionsAsyncReturnsOnCall(i int, result1 bool) {
fake.provisionsAsyncMutex.Lock()
defer fake.provisionsAsyncMutex.Unlock()
fake.ProvisionsAsyncStub = nil
if fake.provisionsAsyncReturnsOnCall == nil {
fake.provisionsAsyncReturnsOnCall = make(map[int]struct {
result1 bool
})
}
fake.provisionsAsyncReturnsOnCall[i] = struct {
result1 bool
}{result1}
}
func (fake *FakeServiceProvider) Unbind(arg1 context.Context, arg2 models.ServiceInstanceDetails, arg3 models.ServiceBindingCredentials) error {
fake.unbindMutex.Lock()
ret, specificReturn := fake.unbindReturnsOnCall[len(fake.unbindArgsForCall)]
fake.unbindArgsForCall = append(fake.unbindArgsForCall, struct {
arg1 context.Context
arg2 models.ServiceInstanceDetails
arg3 models.ServiceBindingCredentials
}{arg1, arg2, arg3})
fake.recordInvocation("Unbind", []interface{}{arg1, arg2, arg3})
fake.unbindMutex.Unlock()
if fake.UnbindStub != nil {
return fake.UnbindStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.unbindReturns
return fakeReturns.result1
}
func (fake *FakeServiceProvider) UnbindCallCount() int {
fake.unbindMutex.RLock()
defer fake.unbindMutex.RUnlock()
return len(fake.unbindArgsForCall)
}
func (fake *FakeServiceProvider) UnbindCalls(stub func(context.Context, models.ServiceInstanceDetails, models.ServiceBindingCredentials) error) {
fake.unbindMutex.Lock()
defer fake.unbindMutex.Unlock()
fake.UnbindStub = stub
}
func (fake *FakeServiceProvider) UnbindArgsForCall(i int) (context.Context, models.ServiceInstanceDetails, models.ServiceBindingCredentials) {
fake.unbindMutex.RLock()
defer fake.unbindMutex.RUnlock()
argsForCall := fake.unbindArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeServiceProvider) UnbindReturns(result1 error) {
fake.unbindMutex.Lock()
defer fake.unbindMutex.Unlock()
fake.UnbindStub = nil
fake.unbindReturns = struct {
result1 error
}{result1}
}
func (fake *FakeServiceProvider) UnbindReturnsOnCall(i int, result1 error) {
fake.unbindMutex.Lock()
defer fake.unbindMutex.Unlock()
fake.UnbindStub = nil
if fake.unbindReturnsOnCall == nil {
fake.unbindReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.unbindReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *FakeServiceProvider) UpdateInstanceDetails(arg1 context.Context, arg2 *models.ServiceInstanceDetails) error {
fake.updateInstanceDetailsMutex.Lock()
ret, specificReturn := fake.updateInstanceDetailsReturnsOnCall[len(fake.updateInstanceDetailsArgsForCall)]
fake.updateInstanceDetailsArgsForCall = append(fake.updateInstanceDetailsArgsForCall, struct {
arg1 context.Context
arg2 *models.ServiceInstanceDetails
}{arg1, arg2})
fake.recordInvocation("UpdateInstanceDetails", []interface{}{arg1, arg2})
fake.updateInstanceDetailsMutex.Unlock()
if fake.UpdateInstanceDetailsStub != nil {
return fake.UpdateInstanceDetailsStub(arg1, arg2)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.updateInstanceDetailsReturns
return fakeReturns.result1
}
func (fake *FakeServiceProvider) UpdateInstanceDetailsCallCount() int {
fake.updateInstanceDetailsMutex.RLock()
defer fake.updateInstanceDetailsMutex.RUnlock()
return len(fake.updateInstanceDetailsArgsForCall)
}
func (fake *FakeServiceProvider) UpdateInstanceDetailsCalls(stub func(context.Context, *models.ServiceInstanceDetails) error) {
fake.updateInstanceDetailsMutex.Lock()
defer fake.updateInstanceDetailsMutex.Unlock()
fake.UpdateInstanceDetailsStub = stub
}
func (fake *FakeServiceProvider) UpdateInstanceDetailsArgsForCall(i int) (context.Context, *models.ServiceInstanceDetails) {
fake.updateInstanceDetailsMutex.RLock()
defer fake.updateInstanceDetailsMutex.RUnlock()
argsForCall := fake.updateInstanceDetailsArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeServiceProvider) UpdateInstanceDetailsReturns(result1 error) {
fake.updateInstanceDetailsMutex.Lock()
defer fake.updateInstanceDetailsMutex.Unlock()
fake.UpdateInstanceDetailsStub = nil
fake.updateInstanceDetailsReturns = struct {
result1 error
}{result1}
}
func (fake *FakeServiceProvider) UpdateInstanceDetailsReturnsOnCall(i int, result1 error) {
fake.updateInstanceDetailsMutex.Lock()
defer fake.updateInstanceDetailsMutex.Unlock()
fake.UpdateInstanceDetailsStub = nil
if fake.updateInstanceDetailsReturnsOnCall == nil {
fake.updateInstanceDetailsReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.updateInstanceDetailsReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *FakeServiceProvider) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.bindMutex.RLock()
defer fake.bindMutex.RUnlock()
fake.buildInstanceCredentialsMutex.RLock()
defer fake.buildInstanceCredentialsMutex.RUnlock()
fake.deprovisionMutex.RLock()
defer fake.deprovisionMutex.RUnlock()
fake.deprovisionsAsyncMutex.RLock()
defer fake.deprovisionsAsyncMutex.RUnlock()
fake.pollInstanceMutex.RLock()
defer fake.pollInstanceMutex.RUnlock()
fake.provisionMutex.RLock()
defer fake.provisionMutex.RUnlock()
fake.provisionsAsyncMutex.RLock()
defer fake.provisionsAsyncMutex.RUnlock()
fake.unbindMutex.RLock()
defer fake.unbindMutex.RUnlock()
fake.updateInstanceDetailsMutex.RLock()
defer fake.updateInstanceDetailsMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeServiceProvider) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ broker.ServiceProvider = new(FakeServiceProvider)
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/policy/policy.go | pkg/broker/policy/policy.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 policy
/*
Package policy defines a way to create simple cascading rule systems similar
to CSS.
A policy is broken into two parts, conditions and declarations. Conditions
are the test that is run when it'd determined if a rule should fire.
Declarations are the values that are set by the rule.
Rules are executed in a low to high precidence order, and values are merged
with the values from higher precidence rules overwriting values with the same
keys that were set earlier.
Rules systems can be painfully difficult to debug and test. This is especially
true because they're often built as a safe way for non-programmers to modify
business process and don't have any way to programatically assert their logic
without resorting to hand-testing.
To combat this issue, this rules system introduces three separate concepts.
1. Conditions are all a strict equality check.
2. Rules are executed from top-to-bottom, eliminating the need for complex
state analysis and backtracking algorithms.
3. There is a built-in system for assertion checking that's exposed to the
rule authors.
*/
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
)
// Conditions are a set of values that can be compared with a base truth and
// return true if all of the facets of the condition match.
type Condition map[string]string
// AppliesTo returns true if all the facets of this condition match the given
// truth.
func (cond Condition) AppliesTo(truth Condition) bool {
for k, v := range cond {
truthValue, ok := truth[k]
if !ok || v != truthValue {
return false
}
}
return true
}
// ValidateKeys ensures all of the keys of the condition exist in the set of
// allowed keys.
func (cond Condition) ValidateKeys(allowedKeys []string) error {
allowedSet := utils.NewStringSet(allowedKeys...)
condKeys := utils.NewStringSetFromStringMapKeys(cond)
invalidKeys := condKeys.Minus(allowedSet)
if invalidKeys.IsEmpty() {
return nil
}
return fmt.Errorf("unknown condition keys: %v condition keys must be one of: %v, check their capitalization and spelling", invalidKeys, allowedKeys)
}
// Policy combines a condition with several sets of values that are set if
// the condition holds true.
type Policy struct {
Comment string `json:"//"`
Condition Condition `json:"if"`
Declarations map[string]interface{} `json:"then"`
}
// PolicyList contains the set of policies.
type PolicyList struct {
// Policies are ordered from least to greatest precidence.
Policies []Policy `json:"policy"`
// Assertions are used to validate the ordering of Policies.
Assertions []Policy `json:"assert"`
}
// Validate checks that the PolicyList struct is valid, that the keys for the
// conditions are valid and that all assertions hold.
func (pl *PolicyList) Validate(validConditionKeys []string) error {
for i, pol := range pl.Policies {
if err := pol.Condition.ValidateKeys(validConditionKeys); err != nil {
return fmt.Errorf("error in policy[%d], comment: %q, error: %v", i, pol.Comment, err)
}
}
return pl.CheckAssertions()
}
// CheckAssertions tests each assertion in the Assertions list against the
// policies list. The condition is used as the ground truth and the
// actions are used as the expected output. If the actions don't match then
// an error is returned.
func (pl *PolicyList) CheckAssertions() error {
for i, assertion := range pl.Assertions {
expected := assertion.Declarations
actual := pl.Apply(assertion.Condition)
if !reflect.DeepEqual(actual, expected) {
return fmt.Errorf("error in assertion[%d], comment: %q, expected: %v, actual: %v", i, assertion.Comment, expected, actual)
}
}
return nil
}
// Apply runs through the list of policies, first to last, and cascades the
// values of each if they match the given condition, returning the merged
// map at the end.
func (pl *PolicyList) Apply(groundTruth Condition) map[string]interface{} {
out := make(map[string]interface{})
for _, policy := range pl.Policies {
if !policy.Condition.AppliesTo(groundTruth) {
continue
}
for k, v := range policy.Declarations {
out[k] = v
}
}
return out
}
// NewPolicyListFromJson creates a PolicyList from the given JSON version.
// It will fail on invalid condition names and failed assertions.
//
// Exactly one of PolicyList or error will be returned.
func NewPolicyListFromJson(value json.RawMessage, validConditionKeys []string) (*PolicyList, error) {
decoder := json.NewDecoder(bytes.NewBuffer(value))
// be noisy if the structure is invalid
decoder.DisallowUnknownFields()
pl := &PolicyList{}
if err := decoder.Decode(pl); err != nil {
return nil, fmt.Errorf("couldn't decode PolicyList from JSON: %v", err)
}
if err := pl.Validate(validConditionKeys); err != nil {
return nil, err
}
return pl, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/broker/policy/policy_test.go | pkg/broker/policy/policy_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 policy
import (
"errors"
"reflect"
"testing"
)
func TestCondition_AppliesTo(t *testing.T) {
cases := map[string]struct {
Condition Condition
Truth Condition
Expected bool
}{
"blank-condition": {
Condition: Condition{},
Truth: Condition{"service_id": "my-service-id", "service_name": "service-name"},
Expected: true,
},
"partial-condition": {
Condition: Condition{"service_id": "my-service-id"},
Truth: Condition{"service_id": "my-service-id", "service_name": "service-name"},
Expected: true,
},
"mismatching-condition": {
Condition: Condition{"service_id": "abc"},
Truth: Condition{"service_id": "my-service-id", "service_name": "service-name"},
Expected: false,
},
"key-not-in-truth": {
Condition: Condition{"service_id": ""},
Truth: Condition{},
Expected: false,
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := tc.Condition.AppliesTo(tc.Truth)
if tc.Expected != actual {
t.Errorf("Expected condition to apply? %t but was: %t", tc.Expected, actual)
}
})
}
}
func TestCondition_ValidateKeys(t *testing.T) {
cases := map[string]struct {
Condition Condition
AllowedKeys []string
Expected error
}{
"blank-condition": {
Condition: Condition{},
AllowedKeys: []string{"service_id"},
Expected: nil,
},
"good-condition": {
Condition: Condition{"service_id": "my-service-id"},
AllowedKeys: []string{"service_id"},
Expected: nil,
},
"key-mismatch": {
Condition: Condition{"service_name": "abc"},
AllowedKeys: []string{"service_id"},
Expected: errors.New("unknown condition keys: [service_name] condition keys must be one of: [service_id], check their capitalization and spelling"),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := tc.Condition.ValidateKeys(tc.AllowedKeys)
if !reflect.DeepEqual(tc.Expected, actual) {
t.Errorf("Expected error: %v got %v", tc.Expected, actual)
}
})
}
}
func TestPolicyList_Validate(t *testing.T) {
cases := map[string]struct {
Policy PolicyList
AllowedKeys []string
Expected error
}{
"blank-policy": {
Policy: PolicyList{},
AllowedKeys: []string{"a", "b"},
Expected: nil,
},
"good-policy": {
Policy: PolicyList{
Policies: []Policy{
{Condition: Condition{"a": "a-value"}, Declarations: map[string]interface{}{"a-fired": true}},
{Condition: Condition{"b": "b-value"}, Declarations: map[string]interface{}{"b-fired": true}},
},
Assertions: []Policy{
{Condition: Condition{"a": "a-value", "b": "b-value"}, Declarations: map[string]interface{}{"a-fired": true, "b-fired": true}},
},
},
AllowedKeys: []string{"a", "b"},
Expected: nil,
},
"bad-keys": {
Policy: PolicyList{
Policies: []Policy{
{Condition: Condition{"unknown": "a-value"}, Comment: "some-user-comment"},
},
},
AllowedKeys: []string{"a", "b"},
Expected: errors.New(`error in policy[0], comment: "some-user-comment", error: unknown condition keys: [unknown] condition keys must be one of: [a b], check their capitalization and spelling`),
},
"bad-assertion": {
Policy: PolicyList{
Policies: []Policy{
{Condition: Condition{"a": "a-value"}, Declarations: map[string]interface{}{"out": false}},
},
Assertions: []Policy{
{Condition: Condition{"a": "a-value"}, Declarations: map[string]interface{}{"out": true}, Comment: "some-assertion"},
},
},
AllowedKeys: []string{"a", "b"},
Expected: errors.New(`error in assertion[0], comment: "some-assertion", expected: map[out:true], actual: map[out:false]`),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := tc.Policy.Validate(tc.AllowedKeys)
if !reflect.DeepEqual(tc.Expected, actual) {
t.Errorf("Expected error: %v got %v", tc.Expected, actual)
}
})
}
}
func TestPolicyList_Apply(t *testing.T) {
cases := map[string]struct {
Policy PolicyList
Truth map[string]string
Expected map[string]interface{}
}{
"cascading-overwrite": {
Policy: PolicyList{
Policies: []Policy{
{Condition: Condition{}, Declarations: map[string]interface{}{"last-fired": 0}},
{Condition: Condition{}, Declarations: map[string]interface{}{"last-fired": 1}},
},
},
Truth: map[string]string{},
Expected: map[string]interface{}{
"last-fired": 1,
},
},
"cascading-merge": {
Policy: PolicyList{
Policies: []Policy{
{Condition: Condition{}, Declarations: map[string]interface{}{"first": 0}},
{Condition: Condition{}, Declarations: map[string]interface{}{"second": 1}},
},
},
Truth: map[string]string{},
Expected: map[string]interface{}{
"first": 0,
"second": 1,
},
},
"no-conditions-match": {
Policy: PolicyList{
Policies: []Policy{
{Condition: Condition{"a": "true"}, Declarations: map[string]interface{}{"first": 0}},
{Condition: Condition{"a": "true"}, Declarations: map[string]interface{}{"second": 1}},
},
},
Truth: map[string]string{},
Expected: map[string]interface{}{},
},
"partial-conditions-match": {
Policy: PolicyList{
Policies: []Policy{
{Condition: Condition{"a": "true"}, Declarations: map[string]interface{}{"last-fired": 0}},
{Condition: Condition{"a": "false"}, Declarations: map[string]interface{}{"last-fired": 1}},
},
},
Truth: map[string]string{"a": "true"},
Expected: map[string]interface{}{
"last-fired": 0,
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := tc.Policy.Apply(tc.Truth)
if !reflect.DeepEqual(tc.Expected, actual) {
t.Errorf("Expected: %v got %v", tc.Expected, actual)
}
})
}
}
func TestNewPolicyListFromJson(t *testing.T) {
cases := map[string]struct {
Json string
AllowedKeys []string
Expected error
}{
"invalid-json": {
Json: `invalid-json`,
AllowedKeys: []string{},
Expected: errors.New("couldn't decode PolicyList from JSON: invalid character 'i' looking for beginning of value"),
},
"unknown-field": {
Json: `{"unknown-field":[]}`,
AllowedKeys: []string{},
Expected: errors.New(`couldn't decode PolicyList from JSON: json: unknown field "unknown-field"`),
},
"bad-key": {
Json: `{"policy":[
{"//":"user-comment", "if":{"unknown-condition":""}}
]}`,
AllowedKeys: []string{},
Expected: errors.New(`error in policy[0], comment: "user-comment", error: unknown condition keys: [unknown-condition] condition keys must be one of: [], check their capitalization and spelling`),
},
"bad-assertion": {
Json: `{
"policy":[
{"if":{}, "then":{"foo":"bar"}},
{"if":{}, "then":{"foo":"bazz"}}
],
"assert":[{"//":"check bad-value", "if":{}, "then":{"foo":"bad-value"}}]
}`,
AllowedKeys: []string{},
Expected: errors.New(`error in assertion[0], comment: "check bad-value", expected: map[foo:bad-value], actual: map[foo:bazz]`),
},
"good-fizzbuzz": {
Json: `{
"policy": [
{"if": {}, "then": {"print":"{{number}}"}},
{"if": {"multiple-of-3":"true"}, "then": {"print":"fizz"}},
{"if": {"multiple-of-5":"true"}, "then": {"print":"buzz"}},
{"if": {"multiple-of-3":"true", "multiple-of-5":"true"}, "then": {"print":"fizzbuzz"}}
],
"assert": [{"if":{"multiple-of-3":"true", "multiple-of-5":"true"}, "then":{"print":"fizzbuzz"}}]
}`,
AllowedKeys: []string{"multiple-of-3", "multiple-of-5"},
Expected: nil,
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
pl, err := NewPolicyListFromJson([]byte(tc.Json), tc.AllowedKeys)
if pl == nil && err == nil || pl != nil && err != nil {
t.Fatalf("Expected exactly one of PolicyList and err to be nil PolicyList: %v, Error: %v", pl, err)
}
if !reflect.DeepEqual(err, tc.Expected) {
t.Errorf("Expected error: %v got: %v", tc.Expected, err)
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/health.go | pkg/server/health.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 server
import (
"database/sql"
"time"
"github.com/gorilla/mux"
"github.com/heptiolabs/healthcheck"
)
// AddHealthHandler creates a new handler for health and liveness checks and
// adds it to the /live and /ready endpoints.
func AddHealthHandler(router *mux.Router, db *sql.DB) healthcheck.Handler {
health := healthcheck.NewHandler()
if db != nil {
health.AddReadinessCheck("database", healthcheck.DatabasePingCheck(db, 2*time.Second))
}
router.HandleFunc("/live", health.LiveEndpoint)
router.HandleFunc("/ready", health.ReadyEndpoint)
return health
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/examples_test.go | pkg/server/examples_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 server
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/client"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin"
)
// Sanity check to make sure GetAllCompleteServiceExamples returns a result
func ExampleGetAllCompleteServiceExamples() {
allServiceExamples, err := GetAllCompleteServiceExamples(builtin.BuiltinBrokerRegistry())
fmt.Println(allServiceExamples != nil)
fmt.Println(err)
// Output:
// true
// <nil>
}
func TestNewExampleHandler(t *testing.T) {
// Validate that the handler returns the correct Content-Type
handler := NewExampleHandler(builtin.BuiltinBrokerRegistry())
request := httptest.NewRequest(http.MethodGet, "/examples", nil)
w := httptest.NewRecorder()
handler(w, request)
if w.Code != http.StatusOK {
t.Errorf("Expected response code: %d got: %d", http.StatusOK, w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "application/json" {
t.Errorf("Expected application/json content type got: %q", contentType)
}
// Validate that the results can be unmarshalled to a CompleteServiceExamples type
body := w.Body.Bytes()
var allExamples []client.CompleteServiceExample
err := json.Unmarshal(body, &allExamples)
if err != nil {
t.Errorf("Error unmarshalling json data: %q", err)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/docs_test.go | pkg/server/docs_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 server
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin"
"github.com/gorilla/mux"
)
func TestNewDocsHandler(t *testing.T) {
registry := builtin.BuiltinBrokerRegistry()
router := mux.NewRouter()
// Test that the handler sets the correct header and contains some imporant
// strings that will indicate (but not prove!) that the rendering was correct.
AddDocsHandler(router, registry)
request := httptest.NewRequest(http.MethodGet, "/docs", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, request)
if w.Code != http.StatusOK {
t.Errorf("Expected response code: %d got: %d", http.StatusOK, w.Code)
}
contentType := w.Header().Get("Content-Type")
if contentType != "text/html" {
t.Errorf("Expected text/html content type got: %q", contentType)
}
importantStrings := []string{"<html", "bootstrap.min.css"}
for _, svc := range registry.GetAllServices() {
importantStrings = append(importantStrings, svc.Name)
}
body := w.Body.Bytes()
for _, is := range importantStrings {
if !bytes.Contains(body, []byte(is)) {
t.Errorf("Expected body to contain the string %q", is)
}
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/health_test.go | pkg/server/health_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 server
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
// Needed to open the sqlite3 database
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
func TestNewHealthHandler(t *testing.T) {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
t.Fatalf("couldn't create database: %v", err)
}
defer os.Remove("test.db")
cases := map[string]struct {
Endpoint string
ExpectedStatus int
ExpectedBody string
LiveErr error
ReadyErr error
}{
"live endpoint full": {
Endpoint: "/live?full=1",
ExpectedStatus: 200,
ExpectedBody: `{"test-live":"OK"}`,
},
"live endpoint minimal": {
Endpoint: "/live",
ExpectedStatus: 200,
ExpectedBody: `{}`,
},
"live endpoint bad": {
Endpoint: "/live?full=1",
ExpectedStatus: 503,
ExpectedBody: `{"test-live":"bad-value"}`,
LiveErr: errors.New("bad-value"),
},
"ready endpoint minimal": {
Endpoint: "/ready",
ExpectedStatus: 200,
ExpectedBody: `{}`,
},
"ready endpoint full": {
Endpoint: "/ready?full=1",
ExpectedStatus: 200,
ExpectedBody: `{"database":"OK","test-live":"OK","test-ready":"OK"}`,
},
"ready endpoint bad liveness": {
Endpoint: "/ready?full=1",
ExpectedStatus: 503,
ExpectedBody: `{"database":"OK","test-live":"bad-value","test-ready":"OK"}`,
LiveErr: errors.New("bad-value"),
},
"ready endpoint bad": {
Endpoint: "/ready?full=1",
ExpectedStatus: 503,
ExpectedBody: `{"database":"OK","test-live":"OK","test-ready":"bad-value"}`,
ReadyErr: errors.New("bad-value"),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
router := mux.NewRouter()
handler := AddHealthHandler(router, db.DB())
handler.AddLivenessCheck("test-live", func() error {
return tc.LiveErr
})
handler.AddReadinessCheck("test-ready", func() error {
return tc.ReadyErr
})
request := httptest.NewRequest(http.MethodGet, tc.Endpoint, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, request)
if w.Code != tc.ExpectedStatus {
t.Fatalf("Expected response code: %v got: %v", tc.ExpectedStatus, w.Code)
}
compacted := &bytes.Buffer{}
if err := json.Compact(compacted, w.Body.Bytes()); err != nil {
t.Fatal(err)
}
if compacted.String() != tc.ExpectedBody {
t.Fatalf("Expected response: %v got: %v", tc.ExpectedBody, compacted.String())
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/docs.go | pkg/server/docs.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 server
import (
"bytes"
"html/template"
"net/http"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/generator"
"github.com/gorilla/mux"
"github.com/russross/blackfriday"
)
var pageTemplate = template.Must(template.New("docs-page").Parse(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>{{.Title}}</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous" />
</head>
<body>
<nav class="navbar navbar-expand navbar-dark sticky-top" style="background-color:#4285F4;">
<a class="navbar-brand" href="#">
<img src="https://cloud.google.com/_static/images/cloud/products/logos/svg/gcp-button-icon.svg" width="30" height="30" class="d-inline-block align-top" alt="">
GCP Service Broker
</a>
<div>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" href="/docs">Docs</a>
</li>
</ul>
</div>
</nav>
<div class="container" id="maincontent">
<br />
{{ .Contents }}
</div>
<!-- Fixups for rendering markdown docs in the browser -->
<script type="text/javascript">
// add classes to the tables to style them nicely
document.querySelectorAll("#maincontent > table").forEach( (node) => {node.classList = "table table-striped"});
</script>
</body>
</html>
`))
// AddDocsHandler creates a handler func that generates HTML documentation for
// the given registry and adds it to the /docs and / routes.
func AddDocsHandler(router *mux.Router, registry broker.BrokerRegistry) {
docsPageMd := generator.CatalogDocumentation(registry)
handler := renderAsPage("Service Broker Documents", docsPageMd)
router.Handle("/docs", handler)
router.Handle("/", handler)
}
func renderAsPage(title, markdownContents string) http.HandlerFunc {
renderer := blackfriday.HtmlRenderer(
blackfriday.EXTENSION_FENCED_CODE|
blackfriday.EXTENSION_AUTOLINK,
title,
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css",
)
page := blackfriday.Markdown([]byte(markdownContents), renderer, 0)
buf := &bytes.Buffer{}
err := pageTemplate.Execute(buf, map[string]interface{}{
"Title": title,
"Contents": template.HTML(page),
})
if err != nil {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
}
}
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(200)
w.Write(buf.Bytes())
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/cf_sharing_test.go | pkg/server/cf_sharing_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 server
import (
"context"
"errors"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/server/fakes"
"github.com/pivotal-cf/brokerapi"
)
func TestCfSharingWraper_Services(t *testing.T) {
cases := map[string]struct {
Services []brokerapi.Service
Error error
}{
"nil services": {
Services: nil,
Error: nil,
},
"empty services": {
Services: []brokerapi.Service{},
Error: nil,
},
"single service": {
Services: []brokerapi.Service{
brokerapi.Service{Name: "foo", Metadata: &brokerapi.ServiceMetadata{}},
},
Error: nil,
},
"missing metadata": {
Services: []brokerapi.Service{
brokerapi.Service{Name: "foo"},
},
Error: nil,
},
"multiple services": {
Services: []brokerapi.Service{
brokerapi.Service{Name: "foo", Metadata: &brokerapi.ServiceMetadata{}},
brokerapi.Service{Name: "bar", Metadata: &brokerapi.ServiceMetadata{}},
},
Error: nil,
},
"error passed": {
Services: nil,
Error: errors.New("returned error"),
},
"services and err": {
Services: []brokerapi.Service{
brokerapi.Service{Name: "foo", Metadata: &brokerapi.ServiceMetadata{}},
brokerapi.Service{Name: "bar", Metadata: &brokerapi.ServiceMetadata{}},
},
Error: errors.New("returned error"),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
wrapped := &fakes.FakeServiceBroker{}
wrapped.ServicesReturns(tc.Services, tc.Error)
sw := NewCfSharingWrapper(wrapped)
services, actualErr := sw.Services(context.Background())
if tc.Error != actualErr {
t.Fatalf("Expected error: %v got: %v", tc.Error, actualErr)
}
if wrapped.ServicesCallCount() != 1 {
t.Errorf("Expected 1 call to Services() got %v", wrapped.ServicesCallCount())
}
if len(services) != len(tc.Services) {
t.Errorf("Expected to get back %d services got %d", len(tc.Services), len(services))
}
for i, svc := range services {
if svc.Metadata == nil {
t.Fatalf("Expected service %d to have metadata, but was nil", i)
}
if svc.Metadata.Shareable == nil {
t.Fatalf("Expected service %d to have shareable, but was nil", i)
}
if *svc.Metadata.Shareable != true {
t.Fatalf("Expected service %d to be shareable, but was %v", i, *svc.Metadata.Shareable)
}
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/cf_sharing.go | pkg/server/cf_sharing.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 server
import (
"context"
"github.com/pivotal-cf/brokerapi"
)
//go:generate counterfeiter -o ./fakes/servicebroker.go ../../vendor/github.com/pivotal-cf/brokerapi ServiceBroker
// CfSharingWrapper enables the Shareable flag for every service provided by
// the broker.
type CfSharingWraper struct {
brokerapi.ServiceBroker
}
// Services augments the response from the wrapped ServiceBroker by adding
// the shareable flag.
func (w *CfSharingWraper) Services(ctx context.Context) (services []brokerapi.Service, err error) {
services, err = w.ServiceBroker.Services(ctx)
for i, _ := range services {
if services[i].Metadata == nil {
services[i].Metadata = &brokerapi.ServiceMetadata{}
}
services[i].Metadata.Shareable = brokerapi.BindableValue(true)
}
return
}
// NewCfSharingWrapper wraps the given servicebroker with the augmenter that
// sets the Shareable flag on all services.
func NewCfSharingWrapper(wrapped brokerapi.ServiceBroker) brokerapi.ServiceBroker {
return &CfSharingWraper{ServiceBroker: wrapped}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/examples.go | pkg/server/examples.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 server
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"sort"
"strings"
"time"
"github.com/spf13/viper"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/client"
)
func GetAllCompleteServiceExamples(registry broker.BrokerRegistry) ([]client.CompleteServiceExample, error) {
var allExamples []client.CompleteServiceExample
services := registry.GetAllServices()
for _, service := range services {
serviceExamples, err := client.GetExamplesForAService(service)
if err != nil {
return nil, err
}
allExamples = append(allExamples, serviceExamples...)
}
// Sort by ServiceName and ExampleName so there's a consistent order in the UI and tests.
sort.Slice(allExamples, func(i int, j int) bool {
if strings.Compare(allExamples[i].ServiceName, allExamples[j].ServiceName) != 0 {
return allExamples[i].ServiceName < allExamples[j].ServiceName
} else {
return allExamples[i].ServiceExample.Name < allExamples[j].ServiceExample.Name
}
})
return allExamples, nil
}
func GetExamplesFromServer() []client.CompleteServiceExample {
var allExamples []client.CompleteServiceExample
url := fmt.Sprintf("http://%s:%d/examples", viper.GetString("api.hostname"), viper.GetInt("api.port"))
serverClient := http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
resp, err := serverClient.Do(req)
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(body, &allExamples)
if err != nil {
log.Fatal(err)
}
return allExamples
}
func NewExampleHandler(registry broker.BrokerRegistry) http.HandlerFunc {
allExamples, err := GetAllCompleteServiceExamples(registry)
if err != nil {
return func(w http.ResponseWriter, rep *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
exampleJSON, err := json.Marshal(allExamples)
if err != nil {
return func(w http.ResponseWriter, rep *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(exampleJSON)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/server/fakes/servicebroker.go | pkg/server/fakes/servicebroker.go | // Code generated by counterfeiter. DO NOT EDIT.
package fakes
import (
context "context"
sync "sync"
brokerapi "github.com/pivotal-cf/brokerapi"
)
type FakeServiceBroker struct {
BindStub func(context.Context, string, string, brokerapi.BindDetails, bool) (brokerapi.Binding, error)
bindMutex sync.RWMutex
bindArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 string
arg4 brokerapi.BindDetails
arg5 bool
}
bindReturns struct {
result1 brokerapi.Binding
result2 error
}
bindReturnsOnCall map[int]struct {
result1 brokerapi.Binding
result2 error
}
DeprovisionStub func(context.Context, string, brokerapi.DeprovisionDetails, bool) (brokerapi.DeprovisionServiceSpec, error)
deprovisionMutex sync.RWMutex
deprovisionArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 brokerapi.DeprovisionDetails
arg4 bool
}
deprovisionReturns struct {
result1 brokerapi.DeprovisionServiceSpec
result2 error
}
deprovisionReturnsOnCall map[int]struct {
result1 brokerapi.DeprovisionServiceSpec
result2 error
}
GetBindingStub func(context.Context, string, string) (brokerapi.GetBindingSpec, error)
getBindingMutex sync.RWMutex
getBindingArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 string
}
getBindingReturns struct {
result1 brokerapi.GetBindingSpec
result2 error
}
getBindingReturnsOnCall map[int]struct {
result1 brokerapi.GetBindingSpec
result2 error
}
GetInstanceStub func(context.Context, string) (brokerapi.GetInstanceDetailsSpec, error)
getInstanceMutex sync.RWMutex
getInstanceArgsForCall []struct {
arg1 context.Context
arg2 string
}
getInstanceReturns struct {
result1 brokerapi.GetInstanceDetailsSpec
result2 error
}
getInstanceReturnsOnCall map[int]struct {
result1 brokerapi.GetInstanceDetailsSpec
result2 error
}
LastBindingOperationStub func(context.Context, string, string, brokerapi.PollDetails) (brokerapi.LastOperation, error)
lastBindingOperationMutex sync.RWMutex
lastBindingOperationArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 string
arg4 brokerapi.PollDetails
}
lastBindingOperationReturns struct {
result1 brokerapi.LastOperation
result2 error
}
lastBindingOperationReturnsOnCall map[int]struct {
result1 brokerapi.LastOperation
result2 error
}
LastOperationStub func(context.Context, string, brokerapi.PollDetails) (brokerapi.LastOperation, error)
lastOperationMutex sync.RWMutex
lastOperationArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 brokerapi.PollDetails
}
lastOperationReturns struct {
result1 brokerapi.LastOperation
result2 error
}
lastOperationReturnsOnCall map[int]struct {
result1 brokerapi.LastOperation
result2 error
}
ProvisionStub func(context.Context, string, brokerapi.ProvisionDetails, bool) (brokerapi.ProvisionedServiceSpec, error)
provisionMutex sync.RWMutex
provisionArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 brokerapi.ProvisionDetails
arg4 bool
}
provisionReturns struct {
result1 brokerapi.ProvisionedServiceSpec
result2 error
}
provisionReturnsOnCall map[int]struct {
result1 brokerapi.ProvisionedServiceSpec
result2 error
}
ServicesStub func(context.Context) ([]brokerapi.Service, error)
servicesMutex sync.RWMutex
servicesArgsForCall []struct {
arg1 context.Context
}
servicesReturns struct {
result1 []brokerapi.Service
result2 error
}
servicesReturnsOnCall map[int]struct {
result1 []brokerapi.Service
result2 error
}
UnbindStub func(context.Context, string, string, brokerapi.UnbindDetails, bool) (brokerapi.UnbindSpec, error)
unbindMutex sync.RWMutex
unbindArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 string
arg4 brokerapi.UnbindDetails
arg5 bool
}
unbindReturns struct {
result1 brokerapi.UnbindSpec
result2 error
}
unbindReturnsOnCall map[int]struct {
result1 brokerapi.UnbindSpec
result2 error
}
UpdateStub func(context.Context, string, brokerapi.UpdateDetails, bool) (brokerapi.UpdateServiceSpec, error)
updateMutex sync.RWMutex
updateArgsForCall []struct {
arg1 context.Context
arg2 string
arg3 brokerapi.UpdateDetails
arg4 bool
}
updateReturns struct {
result1 brokerapi.UpdateServiceSpec
result2 error
}
updateReturnsOnCall map[int]struct {
result1 brokerapi.UpdateServiceSpec
result2 error
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeServiceBroker) Bind(arg1 context.Context, arg2 string, arg3 string, arg4 brokerapi.BindDetails, arg5 bool) (brokerapi.Binding, error) {
fake.bindMutex.Lock()
ret, specificReturn := fake.bindReturnsOnCall[len(fake.bindArgsForCall)]
fake.bindArgsForCall = append(fake.bindArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 string
arg4 brokerapi.BindDetails
arg5 bool
}{arg1, arg2, arg3, arg4, arg5})
fake.recordInvocation("Bind", []interface{}{arg1, arg2, arg3, arg4, arg5})
fake.bindMutex.Unlock()
if fake.BindStub != nil {
return fake.BindStub(arg1, arg2, arg3, arg4, arg5)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.bindReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) BindCallCount() int {
fake.bindMutex.RLock()
defer fake.bindMutex.RUnlock()
return len(fake.bindArgsForCall)
}
func (fake *FakeServiceBroker) BindCalls(stub func(context.Context, string, string, brokerapi.BindDetails, bool) (brokerapi.Binding, error)) {
fake.bindMutex.Lock()
defer fake.bindMutex.Unlock()
fake.BindStub = stub
}
func (fake *FakeServiceBroker) BindArgsForCall(i int) (context.Context, string, string, brokerapi.BindDetails, bool) {
fake.bindMutex.RLock()
defer fake.bindMutex.RUnlock()
argsForCall := fake.bindArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5
}
func (fake *FakeServiceBroker) BindReturns(result1 brokerapi.Binding, result2 error) {
fake.bindMutex.Lock()
defer fake.bindMutex.Unlock()
fake.BindStub = nil
fake.bindReturns = struct {
result1 brokerapi.Binding
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) BindReturnsOnCall(i int, result1 brokerapi.Binding, result2 error) {
fake.bindMutex.Lock()
defer fake.bindMutex.Unlock()
fake.BindStub = nil
if fake.bindReturnsOnCall == nil {
fake.bindReturnsOnCall = make(map[int]struct {
result1 brokerapi.Binding
result2 error
})
}
fake.bindReturnsOnCall[i] = struct {
result1 brokerapi.Binding
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) Deprovision(arg1 context.Context, arg2 string, arg3 brokerapi.DeprovisionDetails, arg4 bool) (brokerapi.DeprovisionServiceSpec, error) {
fake.deprovisionMutex.Lock()
ret, specificReturn := fake.deprovisionReturnsOnCall[len(fake.deprovisionArgsForCall)]
fake.deprovisionArgsForCall = append(fake.deprovisionArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 brokerapi.DeprovisionDetails
arg4 bool
}{arg1, arg2, arg3, arg4})
fake.recordInvocation("Deprovision", []interface{}{arg1, arg2, arg3, arg4})
fake.deprovisionMutex.Unlock()
if fake.DeprovisionStub != nil {
return fake.DeprovisionStub(arg1, arg2, arg3, arg4)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.deprovisionReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) DeprovisionCallCount() int {
fake.deprovisionMutex.RLock()
defer fake.deprovisionMutex.RUnlock()
return len(fake.deprovisionArgsForCall)
}
func (fake *FakeServiceBroker) DeprovisionCalls(stub func(context.Context, string, brokerapi.DeprovisionDetails, bool) (brokerapi.DeprovisionServiceSpec, error)) {
fake.deprovisionMutex.Lock()
defer fake.deprovisionMutex.Unlock()
fake.DeprovisionStub = stub
}
func (fake *FakeServiceBroker) DeprovisionArgsForCall(i int) (context.Context, string, brokerapi.DeprovisionDetails, bool) {
fake.deprovisionMutex.RLock()
defer fake.deprovisionMutex.RUnlock()
argsForCall := fake.deprovisionArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}
func (fake *FakeServiceBroker) DeprovisionReturns(result1 brokerapi.DeprovisionServiceSpec, result2 error) {
fake.deprovisionMutex.Lock()
defer fake.deprovisionMutex.Unlock()
fake.DeprovisionStub = nil
fake.deprovisionReturns = struct {
result1 brokerapi.DeprovisionServiceSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) DeprovisionReturnsOnCall(i int, result1 brokerapi.DeprovisionServiceSpec, result2 error) {
fake.deprovisionMutex.Lock()
defer fake.deprovisionMutex.Unlock()
fake.DeprovisionStub = nil
if fake.deprovisionReturnsOnCall == nil {
fake.deprovisionReturnsOnCall = make(map[int]struct {
result1 brokerapi.DeprovisionServiceSpec
result2 error
})
}
fake.deprovisionReturnsOnCall[i] = struct {
result1 brokerapi.DeprovisionServiceSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) GetBinding(arg1 context.Context, arg2 string, arg3 string) (brokerapi.GetBindingSpec, error) {
fake.getBindingMutex.Lock()
ret, specificReturn := fake.getBindingReturnsOnCall[len(fake.getBindingArgsForCall)]
fake.getBindingArgsForCall = append(fake.getBindingArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 string
}{arg1, arg2, arg3})
fake.recordInvocation("GetBinding", []interface{}{arg1, arg2, arg3})
fake.getBindingMutex.Unlock()
if fake.GetBindingStub != nil {
return fake.GetBindingStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.getBindingReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) GetBindingCallCount() int {
fake.getBindingMutex.RLock()
defer fake.getBindingMutex.RUnlock()
return len(fake.getBindingArgsForCall)
}
func (fake *FakeServiceBroker) GetBindingCalls(stub func(context.Context, string, string) (brokerapi.GetBindingSpec, error)) {
fake.getBindingMutex.Lock()
defer fake.getBindingMutex.Unlock()
fake.GetBindingStub = stub
}
func (fake *FakeServiceBroker) GetBindingArgsForCall(i int) (context.Context, string, string) {
fake.getBindingMutex.RLock()
defer fake.getBindingMutex.RUnlock()
argsForCall := fake.getBindingArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeServiceBroker) GetBindingReturns(result1 brokerapi.GetBindingSpec, result2 error) {
fake.getBindingMutex.Lock()
defer fake.getBindingMutex.Unlock()
fake.GetBindingStub = nil
fake.getBindingReturns = struct {
result1 brokerapi.GetBindingSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) GetBindingReturnsOnCall(i int, result1 brokerapi.GetBindingSpec, result2 error) {
fake.getBindingMutex.Lock()
defer fake.getBindingMutex.Unlock()
fake.GetBindingStub = nil
if fake.getBindingReturnsOnCall == nil {
fake.getBindingReturnsOnCall = make(map[int]struct {
result1 brokerapi.GetBindingSpec
result2 error
})
}
fake.getBindingReturnsOnCall[i] = struct {
result1 brokerapi.GetBindingSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) GetInstance(arg1 context.Context, arg2 string) (brokerapi.GetInstanceDetailsSpec, error) {
fake.getInstanceMutex.Lock()
ret, specificReturn := fake.getInstanceReturnsOnCall[len(fake.getInstanceArgsForCall)]
fake.getInstanceArgsForCall = append(fake.getInstanceArgsForCall, struct {
arg1 context.Context
arg2 string
}{arg1, arg2})
fake.recordInvocation("GetInstance", []interface{}{arg1, arg2})
fake.getInstanceMutex.Unlock()
if fake.GetInstanceStub != nil {
return fake.GetInstanceStub(arg1, arg2)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.getInstanceReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) GetInstanceCallCount() int {
fake.getInstanceMutex.RLock()
defer fake.getInstanceMutex.RUnlock()
return len(fake.getInstanceArgsForCall)
}
func (fake *FakeServiceBroker) GetInstanceCalls(stub func(context.Context, string) (brokerapi.GetInstanceDetailsSpec, error)) {
fake.getInstanceMutex.Lock()
defer fake.getInstanceMutex.Unlock()
fake.GetInstanceStub = stub
}
func (fake *FakeServiceBroker) GetInstanceArgsForCall(i int) (context.Context, string) {
fake.getInstanceMutex.RLock()
defer fake.getInstanceMutex.RUnlock()
argsForCall := fake.getInstanceArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeServiceBroker) GetInstanceReturns(result1 brokerapi.GetInstanceDetailsSpec, result2 error) {
fake.getInstanceMutex.Lock()
defer fake.getInstanceMutex.Unlock()
fake.GetInstanceStub = nil
fake.getInstanceReturns = struct {
result1 brokerapi.GetInstanceDetailsSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) GetInstanceReturnsOnCall(i int, result1 brokerapi.GetInstanceDetailsSpec, result2 error) {
fake.getInstanceMutex.Lock()
defer fake.getInstanceMutex.Unlock()
fake.GetInstanceStub = nil
if fake.getInstanceReturnsOnCall == nil {
fake.getInstanceReturnsOnCall = make(map[int]struct {
result1 brokerapi.GetInstanceDetailsSpec
result2 error
})
}
fake.getInstanceReturnsOnCall[i] = struct {
result1 brokerapi.GetInstanceDetailsSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) LastBindingOperation(arg1 context.Context, arg2 string, arg3 string, arg4 brokerapi.PollDetails) (brokerapi.LastOperation, error) {
fake.lastBindingOperationMutex.Lock()
ret, specificReturn := fake.lastBindingOperationReturnsOnCall[len(fake.lastBindingOperationArgsForCall)]
fake.lastBindingOperationArgsForCall = append(fake.lastBindingOperationArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 string
arg4 brokerapi.PollDetails
}{arg1, arg2, arg3, arg4})
fake.recordInvocation("LastBindingOperation", []interface{}{arg1, arg2, arg3, arg4})
fake.lastBindingOperationMutex.Unlock()
if fake.LastBindingOperationStub != nil {
return fake.LastBindingOperationStub(arg1, arg2, arg3, arg4)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.lastBindingOperationReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) LastBindingOperationCallCount() int {
fake.lastBindingOperationMutex.RLock()
defer fake.lastBindingOperationMutex.RUnlock()
return len(fake.lastBindingOperationArgsForCall)
}
func (fake *FakeServiceBroker) LastBindingOperationCalls(stub func(context.Context, string, string, brokerapi.PollDetails) (brokerapi.LastOperation, error)) {
fake.lastBindingOperationMutex.Lock()
defer fake.lastBindingOperationMutex.Unlock()
fake.LastBindingOperationStub = stub
}
func (fake *FakeServiceBroker) LastBindingOperationArgsForCall(i int) (context.Context, string, string, brokerapi.PollDetails) {
fake.lastBindingOperationMutex.RLock()
defer fake.lastBindingOperationMutex.RUnlock()
argsForCall := fake.lastBindingOperationArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}
func (fake *FakeServiceBroker) LastBindingOperationReturns(result1 brokerapi.LastOperation, result2 error) {
fake.lastBindingOperationMutex.Lock()
defer fake.lastBindingOperationMutex.Unlock()
fake.LastBindingOperationStub = nil
fake.lastBindingOperationReturns = struct {
result1 brokerapi.LastOperation
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) LastBindingOperationReturnsOnCall(i int, result1 brokerapi.LastOperation, result2 error) {
fake.lastBindingOperationMutex.Lock()
defer fake.lastBindingOperationMutex.Unlock()
fake.LastBindingOperationStub = nil
if fake.lastBindingOperationReturnsOnCall == nil {
fake.lastBindingOperationReturnsOnCall = make(map[int]struct {
result1 brokerapi.LastOperation
result2 error
})
}
fake.lastBindingOperationReturnsOnCall[i] = struct {
result1 brokerapi.LastOperation
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) LastOperation(arg1 context.Context, arg2 string, arg3 brokerapi.PollDetails) (brokerapi.LastOperation, error) {
fake.lastOperationMutex.Lock()
ret, specificReturn := fake.lastOperationReturnsOnCall[len(fake.lastOperationArgsForCall)]
fake.lastOperationArgsForCall = append(fake.lastOperationArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 brokerapi.PollDetails
}{arg1, arg2, arg3})
fake.recordInvocation("LastOperation", []interface{}{arg1, arg2, arg3})
fake.lastOperationMutex.Unlock()
if fake.LastOperationStub != nil {
return fake.LastOperationStub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.lastOperationReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) LastOperationCallCount() int {
fake.lastOperationMutex.RLock()
defer fake.lastOperationMutex.RUnlock()
return len(fake.lastOperationArgsForCall)
}
func (fake *FakeServiceBroker) LastOperationCalls(stub func(context.Context, string, brokerapi.PollDetails) (brokerapi.LastOperation, error)) {
fake.lastOperationMutex.Lock()
defer fake.lastOperationMutex.Unlock()
fake.LastOperationStub = stub
}
func (fake *FakeServiceBroker) LastOperationArgsForCall(i int) (context.Context, string, brokerapi.PollDetails) {
fake.lastOperationMutex.RLock()
defer fake.lastOperationMutex.RUnlock()
argsForCall := fake.lastOperationArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeServiceBroker) LastOperationReturns(result1 brokerapi.LastOperation, result2 error) {
fake.lastOperationMutex.Lock()
defer fake.lastOperationMutex.Unlock()
fake.LastOperationStub = nil
fake.lastOperationReturns = struct {
result1 brokerapi.LastOperation
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) LastOperationReturnsOnCall(i int, result1 brokerapi.LastOperation, result2 error) {
fake.lastOperationMutex.Lock()
defer fake.lastOperationMutex.Unlock()
fake.LastOperationStub = nil
if fake.lastOperationReturnsOnCall == nil {
fake.lastOperationReturnsOnCall = make(map[int]struct {
result1 brokerapi.LastOperation
result2 error
})
}
fake.lastOperationReturnsOnCall[i] = struct {
result1 brokerapi.LastOperation
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) Provision(arg1 context.Context, arg2 string, arg3 brokerapi.ProvisionDetails, arg4 bool) (brokerapi.ProvisionedServiceSpec, error) {
fake.provisionMutex.Lock()
ret, specificReturn := fake.provisionReturnsOnCall[len(fake.provisionArgsForCall)]
fake.provisionArgsForCall = append(fake.provisionArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 brokerapi.ProvisionDetails
arg4 bool
}{arg1, arg2, arg3, arg4})
fake.recordInvocation("Provision", []interface{}{arg1, arg2, arg3, arg4})
fake.provisionMutex.Unlock()
if fake.ProvisionStub != nil {
return fake.ProvisionStub(arg1, arg2, arg3, arg4)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.provisionReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) ProvisionCallCount() int {
fake.provisionMutex.RLock()
defer fake.provisionMutex.RUnlock()
return len(fake.provisionArgsForCall)
}
func (fake *FakeServiceBroker) ProvisionCalls(stub func(context.Context, string, brokerapi.ProvisionDetails, bool) (brokerapi.ProvisionedServiceSpec, error)) {
fake.provisionMutex.Lock()
defer fake.provisionMutex.Unlock()
fake.ProvisionStub = stub
}
func (fake *FakeServiceBroker) ProvisionArgsForCall(i int) (context.Context, string, brokerapi.ProvisionDetails, bool) {
fake.provisionMutex.RLock()
defer fake.provisionMutex.RUnlock()
argsForCall := fake.provisionArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}
func (fake *FakeServiceBroker) ProvisionReturns(result1 brokerapi.ProvisionedServiceSpec, result2 error) {
fake.provisionMutex.Lock()
defer fake.provisionMutex.Unlock()
fake.ProvisionStub = nil
fake.provisionReturns = struct {
result1 brokerapi.ProvisionedServiceSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) ProvisionReturnsOnCall(i int, result1 brokerapi.ProvisionedServiceSpec, result2 error) {
fake.provisionMutex.Lock()
defer fake.provisionMutex.Unlock()
fake.ProvisionStub = nil
if fake.provisionReturnsOnCall == nil {
fake.provisionReturnsOnCall = make(map[int]struct {
result1 brokerapi.ProvisionedServiceSpec
result2 error
})
}
fake.provisionReturnsOnCall[i] = struct {
result1 brokerapi.ProvisionedServiceSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) Services(arg1 context.Context) ([]brokerapi.Service, error) {
fake.servicesMutex.Lock()
ret, specificReturn := fake.servicesReturnsOnCall[len(fake.servicesArgsForCall)]
fake.servicesArgsForCall = append(fake.servicesArgsForCall, struct {
arg1 context.Context
}{arg1})
fake.recordInvocation("Services", []interface{}{arg1})
fake.servicesMutex.Unlock()
if fake.ServicesStub != nil {
return fake.ServicesStub(arg1)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.servicesReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) ServicesCallCount() int {
fake.servicesMutex.RLock()
defer fake.servicesMutex.RUnlock()
return len(fake.servicesArgsForCall)
}
func (fake *FakeServiceBroker) ServicesCalls(stub func(context.Context) ([]brokerapi.Service, error)) {
fake.servicesMutex.Lock()
defer fake.servicesMutex.Unlock()
fake.ServicesStub = stub
}
func (fake *FakeServiceBroker) ServicesArgsForCall(i int) context.Context {
fake.servicesMutex.RLock()
defer fake.servicesMutex.RUnlock()
argsForCall := fake.servicesArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeServiceBroker) ServicesReturns(result1 []brokerapi.Service, result2 error) {
fake.servicesMutex.Lock()
defer fake.servicesMutex.Unlock()
fake.ServicesStub = nil
fake.servicesReturns = struct {
result1 []brokerapi.Service
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) ServicesReturnsOnCall(i int, result1 []brokerapi.Service, result2 error) {
fake.servicesMutex.Lock()
defer fake.servicesMutex.Unlock()
fake.ServicesStub = nil
if fake.servicesReturnsOnCall == nil {
fake.servicesReturnsOnCall = make(map[int]struct {
result1 []brokerapi.Service
result2 error
})
}
fake.servicesReturnsOnCall[i] = struct {
result1 []brokerapi.Service
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) Unbind(arg1 context.Context, arg2 string, arg3 string, arg4 brokerapi.UnbindDetails, arg5 bool) (brokerapi.UnbindSpec, error) {
fake.unbindMutex.Lock()
ret, specificReturn := fake.unbindReturnsOnCall[len(fake.unbindArgsForCall)]
fake.unbindArgsForCall = append(fake.unbindArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 string
arg4 brokerapi.UnbindDetails
arg5 bool
}{arg1, arg2, arg3, arg4, arg5})
fake.recordInvocation("Unbind", []interface{}{arg1, arg2, arg3, arg4, arg5})
fake.unbindMutex.Unlock()
if fake.UnbindStub != nil {
return fake.UnbindStub(arg1, arg2, arg3, arg4, arg5)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.unbindReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) UnbindCallCount() int {
fake.unbindMutex.RLock()
defer fake.unbindMutex.RUnlock()
return len(fake.unbindArgsForCall)
}
func (fake *FakeServiceBroker) UnbindCalls(stub func(context.Context, string, string, brokerapi.UnbindDetails, bool) (brokerapi.UnbindSpec, error)) {
fake.unbindMutex.Lock()
defer fake.unbindMutex.Unlock()
fake.UnbindStub = stub
}
func (fake *FakeServiceBroker) UnbindArgsForCall(i int) (context.Context, string, string, brokerapi.UnbindDetails, bool) {
fake.unbindMutex.RLock()
defer fake.unbindMutex.RUnlock()
argsForCall := fake.unbindArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5
}
func (fake *FakeServiceBroker) UnbindReturns(result1 brokerapi.UnbindSpec, result2 error) {
fake.unbindMutex.Lock()
defer fake.unbindMutex.Unlock()
fake.UnbindStub = nil
fake.unbindReturns = struct {
result1 brokerapi.UnbindSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) UnbindReturnsOnCall(i int, result1 brokerapi.UnbindSpec, result2 error) {
fake.unbindMutex.Lock()
defer fake.unbindMutex.Unlock()
fake.UnbindStub = nil
if fake.unbindReturnsOnCall == nil {
fake.unbindReturnsOnCall = make(map[int]struct {
result1 brokerapi.UnbindSpec
result2 error
})
}
fake.unbindReturnsOnCall[i] = struct {
result1 brokerapi.UnbindSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) Update(arg1 context.Context, arg2 string, arg3 brokerapi.UpdateDetails, arg4 bool) (brokerapi.UpdateServiceSpec, error) {
fake.updateMutex.Lock()
ret, specificReturn := fake.updateReturnsOnCall[len(fake.updateArgsForCall)]
fake.updateArgsForCall = append(fake.updateArgsForCall, struct {
arg1 context.Context
arg2 string
arg3 brokerapi.UpdateDetails
arg4 bool
}{arg1, arg2, arg3, arg4})
fake.recordInvocation("Update", []interface{}{arg1, arg2, arg3, arg4})
fake.updateMutex.Unlock()
if fake.UpdateStub != nil {
return fake.UpdateStub(arg1, arg2, arg3, arg4)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.updateReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceBroker) UpdateCallCount() int {
fake.updateMutex.RLock()
defer fake.updateMutex.RUnlock()
return len(fake.updateArgsForCall)
}
func (fake *FakeServiceBroker) UpdateCalls(stub func(context.Context, string, brokerapi.UpdateDetails, bool) (brokerapi.UpdateServiceSpec, error)) {
fake.updateMutex.Lock()
defer fake.updateMutex.Unlock()
fake.UpdateStub = stub
}
func (fake *FakeServiceBroker) UpdateArgsForCall(i int) (context.Context, string, brokerapi.UpdateDetails, bool) {
fake.updateMutex.RLock()
defer fake.updateMutex.RUnlock()
argsForCall := fake.updateArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}
func (fake *FakeServiceBroker) UpdateReturns(result1 brokerapi.UpdateServiceSpec, result2 error) {
fake.updateMutex.Lock()
defer fake.updateMutex.Unlock()
fake.UpdateStub = nil
fake.updateReturns = struct {
result1 brokerapi.UpdateServiceSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) UpdateReturnsOnCall(i int, result1 brokerapi.UpdateServiceSpec, result2 error) {
fake.updateMutex.Lock()
defer fake.updateMutex.Unlock()
fake.UpdateStub = nil
if fake.updateReturnsOnCall == nil {
fake.updateReturnsOnCall = make(map[int]struct {
result1 brokerapi.UpdateServiceSpec
result2 error
})
}
fake.updateReturnsOnCall[i] = struct {
result1 brokerapi.UpdateServiceSpec
result2 error
}{result1, result2}
}
func (fake *FakeServiceBroker) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.bindMutex.RLock()
defer fake.bindMutex.RUnlock()
fake.deprovisionMutex.RLock()
defer fake.deprovisionMutex.RUnlock()
fake.getBindingMutex.RLock()
defer fake.getBindingMutex.RUnlock()
fake.getInstanceMutex.RLock()
defer fake.getInstanceMutex.RUnlock()
fake.lastBindingOperationMutex.RLock()
defer fake.lastBindingOperationMutex.RUnlock()
fake.lastOperationMutex.RLock()
defer fake.lastOperationMutex.RUnlock()
fake.provisionMutex.RLock()
defer fake.provisionMutex.RUnlock()
fake.servicesMutex.RLock()
defer fake.servicesMutex.RUnlock()
fake.unbindMutex.RLock()
defer fake.unbindMutex.RUnlock()
fake.updateMutex.RLock()
defer fake.updateMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeServiceBroker) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ brokerapi.ServiceBroker = new(FakeServiceBroker)
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/config/migration/diff.go | pkg/config/migration/diff.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 migration
import "github.com/GoogleCloudPlatform/gcp-service-broker/utils"
// Diff holds the difference between two strings.
type Diff struct {
Old string `yaml:"old,omitempty"`
New string `yaml:"new"` // new is intentionally not omitempty to show change
}
// DiffStringMap creates a diff between the two maps.
func DiffStringMap(old, new map[string]string) map[string]Diff {
allKeys := utils.NewStringSetFromStringMapKeys(old)
newKeys := utils.NewStringSetFromStringMapKeys(new)
allKeys.Add(newKeys.ToSlice()...)
out := make(map[string]Diff)
for _, k := range allKeys.ToSlice() {
if old[k] != new[k] {
out[k] = Diff{Old: old[k], New: new[k]}
}
}
return out
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/config/migration/migration.go | pkg/config/migration/migration.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 migration
import (
"bytes"
"fmt"
"os"
"strings"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
)
// Migration holds the information necessary to modify the values in the tile.
type Migration struct {
Name string
TileScript string
GoFunc func(env map[string]string)
}
func deleteMigration(name string, env []string) Migration {
js := ``
for _, v := range env {
js += "delete properties.properties['.properties." + strings.ToLower(v) + "'];\n"
}
return Migration{
Name: name,
TileScript: js,
GoFunc: func(envMap map[string]string) {
for _, v := range env {
delete(envMap, v)
}
},
}
}
// NoOp is an empty migration.
func NoOp() Migration {
return Migration{
Name: "Noop",
TileScript: ``,
GoFunc: func(envMap map[string]string) {},
}
}
// DeleteWhitelistKeys removes the whitelist keys used prior to 4.0
func DeleteWhitelistKeys() Migration {
whitelistKeys := []string{
"GSB_SERVICE_GOOGLE_BIGQUERY_WHITELIST",
"GSB_SERVICE_GOOGLE_BIGTABLE_WHITELIST",
"GSB_SERVICE_GOOGLE_CLOUDSQL_MYSQL_WHITELIST",
"GSB_SERVICE_GOOGLE_CLOUDSQL_POSTGRES_WHITELIST",
"GSB_SERVICE_GOOGLE_ML_APIS_WHITELIST",
"GSB_SERVICE_GOOGLE_PUBSUB_WHITELIST",
"GSB_SERVICE_GOOGLE_SPANNER_WHITELIST",
"GSB_SERVICE_GOOGLE_STORAGE_WHITELIST",
}
return deleteMigration("Delete whitelist keys from 4.x", whitelistKeys)
}
// migrations returns a list of all migrations to be performed in order.
func migrations() []Migration {
return []Migration{
DeleteWhitelistKeys(),
}
}
// FullMigration holds the complete migration path.
func FullMigration() Migration {
migrations := migrations()
var buf bytes.Buffer
for i, migration := range migrations {
fmt.Fprintln(&buf, "{")
fmt.Fprintf(&buf, "// migration: %d, %s\n", i, migration.Name)
fmt.Fprintln(&buf, migration.TileScript)
fmt.Fprintln(&buf, "}")
}
return Migration{
Name: "Full Migration",
TileScript: string(buf.Bytes()),
GoFunc: func(env map[string]string) {
for _, migration := range migrations {
migration.GoFunc(env)
}
},
}
}
// MigrateEnv migrates the currently set environment variables and returns
// the diff.
func MigrateEnv() map[string]Diff {
env := splitEnv()
orig := utils.CopyStringMap(env)
FullMigration().GoFunc(env)
return DiffStringMap(orig, env)
}
// splitEnv splits os.Environ style environment variables that
// are in an array of "key=value" strings.
func splitEnv() map[string]string {
envMap := make(map[string]string)
for _, e := range os.Environ() {
split := strings.Split(e, "=")
envMap[split[0]] = strings.Join(split[1:], "=")
}
return envMap
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/config/migration/diff_test.go | pkg/config/migration/diff_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 migration
import (
"reflect"
"testing"
)
func TestDiffStringMap(t *testing.T) {
cases := map[string]struct {
Old map[string]string
New map[string]string
Expected map[string]Diff
}{
"same": {
Old: map[string]string{"a": "b"},
New: map[string]string{"a": "b"},
Expected: map[string]Diff{},
},
"removed": {
Old: map[string]string{"a": "old"},
New: map[string]string{},
Expected: map[string]Diff{"a": Diff{Old: "old", New: ""}},
},
"added": {
Old: map[string]string{},
New: map[string]string{"a": "new"},
Expected: map[string]Diff{"a": Diff{Old: "", New: "new"}},
},
"changed": {
Old: map[string]string{"a": "old"},
New: map[string]string{"a": "new"},
Expected: map[string]Diff{"a": Diff{Old: "old", New: "new"}},
},
"full-gambit": {
Old: map[string]string{
"removed": "removed",
"changed": "orig",
},
New: map[string]string{
"changed": "new",
"added": "added",
},
Expected: map[string]Diff{
"removed": Diff{Old: "removed", New: ""},
"changed": Diff{Old: "orig", New: "new"},
"added": Diff{Old: "", New: "added"},
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := DiffStringMap(tc.Old, tc.New)
if !reflect.DeepEqual(tc.Expected, actual) {
t.Errorf("Expected: %#v Actual: %#v", tc.Expected, actual)
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/config/migration/migration_test.go | pkg/config/migration/migration_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 migration
import (
"encoding/json"
"reflect"
"strings"
"testing"
"github.com/robertkrimen/otto"
)
const tileToEnvFunctionJs = `
function defnToEnv(defn) {
if (defn.type !== 'collection') {
return defn.value;
}
var collectionEntries = defn.value;
var out = [];
for (var i = 0; i < collectionEntries.length; i++) {
var element = collectionEntries[i];
var elementObj = {};
for (var elementKey in element) {
elementObj[elementKey] = defnToEnv(element[elementKey]);
}
out.push(elementObj);
}
return JSON.stringify(out, null, ' ')
}
function tile2env(properties) {
var inner = properties["properties"];
var env = {};
for(var key in inner) {
// skip non properties
if(key.indexOf(".properties.") !== 0){
continue;
}
// strip the .properties. prefix
var envVar = key.substr(12).toUpperCase();
var defn = inner[key];
env[envVar] = '' + defnToEnv(defn);
}
return JSON.stringify(env);
}
properties = {{properties}};
{{migrationScript}}
tile2env(properties);
`
func GetMigrationResults(t *testing.T, tilePropertiesJSON, migrationScript string) map[string]string {
t.Helper()
vm := otto.New()
script := tileToEnvFunctionJs
replacer := strings.NewReplacer(
"{{properties}}", tilePropertiesJSON,
"{{migrationScript}}", migrationScript)
script = replacer.Replace(script)
t.Log(script)
result, err := vm.Run(script)
if err != nil {
t.Fatal(err)
}
value, err := result.ToString()
if err != nil {
t.Fatal(err)
}
out := map[string]string{}
if err := json.Unmarshal([]byte(value), &out); err != nil {
t.Fatal(err)
}
return out
}
type MigrationTest struct {
TileProperties string
Migration Migration
ExpectedEnv map[string]string
}
func (m *MigrationTest) Run(t *testing.T) {
t.Log("Running JS migration function")
m.runJs(t)
t.Log("Running go migration function")
m.runGo(t)
}
func (m *MigrationTest) runJs(t *testing.T) {
out := GetMigrationResults(t, m.TileProperties, m.Migration.TileScript)
if !reflect.DeepEqual(out, m.ExpectedEnv) {
t.Errorf("Expected: %v Got: %v", m.ExpectedEnv, out)
}
}
func (m *MigrationTest) runGo(t *testing.T) {
// runGo runs a no-op JS migration to get the environment variables as the
// application would see them, then applies the go migration function to
// ensure it produces the same result for people migrating by hand as the
// JavaScript does for the tile users
envFromTile := GetMigrationResults(t, m.TileProperties, "")
m.Migration.GoFunc(envFromTile)
if !reflect.DeepEqual(envFromTile, m.ExpectedEnv) {
t.Errorf("Expected: %v Got: %v", m.ExpectedEnv, envFromTile)
}
}
// TestNoOp is primarially to ensure the embedded JavaScript works.
func TestNoOp(t *testing.T) {
cases := map[string]MigrationTest{
"basic": {
TileProperties: `
{
"properties": {
".properties.org": {
"type": "string",
"configurable": true,
"credential": false,
"value": "system",
"optional": false
},
".properties.space": {
"type": "string",
"configurable": true,
"credential": false,
"value": "gcp-service-broker-space",
"optional": false
}
}
}
`,
Migration: NoOp(),
ExpectedEnv: map[string]string{
"ORG": "system",
"SPACE": "gcp-service-broker-space",
},
},
"empty": {
TileProperties: `{"properties":{}}`,
Migration: NoOp(),
ExpectedEnv: map[string]string{},
},
"collection": {
TileProperties: `
{
"properties": {
".properties.storage_custom_plans": {
"type": "collection",
"configurable": true,
"credential": false,
"value": [
{
"guid": {
"type": "uuid",
"configurable": false,
"credential": false,
"value": "424b9afa-b31a-4517-a764-fbd137e58d3d",
"optional": false
},
"name": {
"type": "string",
"configurable": true,
"credential": false,
"value": "custom-storage-plan",
"optional": false
},
"display_name": {
"type": "string",
"configurable": true,
"credential": false,
"value": "custom cloud storage plan",
"optional": false
},
"description": {
"type": "string",
"configurable": true,
"credential": false,
"value": "custom storage plan description",
"optional": false
},
"service": {
"type": "dropdown_select",
"configurable": false,
"credential": false,
"value": "b9e4332e-b42b-4680-bda5-ea1506797474",
"optional": false,
"options": [
{
"label": "Google Cloud Storage",
"value": "b9e4332e-b42b-4680-bda5-ea1506797474"
}
]
},
"storage_class": {
"type": "string",
"configurable": true,
"credential": false,
"value": "standard",
"optional": false
}
}
],
"optional": true
}
}
}`,
Migration: NoOp(),
ExpectedEnv: map[string]string{
"STORAGE_CUSTOM_PLANS": `[
{
"description": "custom storage plan description",
"display_name": "custom cloud storage plan",
"guid": "424b9afa-b31a-4517-a764-fbd137e58d3d",
"name": "custom-storage-plan",
"service": "b9e4332e-b42b-4680-bda5-ea1506797474",
"storage_class": "standard"
}
]`,
},
},
}
for tn, tc := range cases {
t.Run(tn, tc.Run)
}
}
func TestDeleteWhitelistKeys(t *testing.T) {
cases := map[string]MigrationTest{
"no-overlap": {
TileProperties: `
{
"properties": {
".properties.org": {
"type": "string",
"configurable": true,
"credential": false,
"value": "system",
"optional": false
}
}
}`,
Migration: DeleteWhitelistKeys(),
ExpectedEnv: map[string]string{"ORG": "system"},
},
"one-key": {
TileProperties: `
{
"properties": {
".properties.org": {"type": "string", "value": "system"},
".properties.gsb_service_google_bigquery_whitelist": { "value": 1 },
}
}`,
Migration: DeleteWhitelistKeys(),
ExpectedEnv: map[string]string{"ORG": "system"},
},
"all-keys": {
TileProperties: `
{
"properties": {
".properties.gsb_service_google_bigquery_whitelist": { "value": 1 },
".properties.gsb_service_google_bigtable_whitelist": { "value": 1 },
".properties.gsb_service_google_cloudsql_mysql_whitelist": { "value": 1 },
".properties.gsb_service_google_cloudsql_postgres_whitelist": { "value": 1 },
".properties.gsb_service_google_ml_apis_whitelist": { "value": 1 },
".properties.gsb_service_google_pubsub_whitelist": { "value": 1 },
".properties.gsb_service_google_spanner_whitelist": { "value": 1 },
".properties.gsb_service_google_storage_whitelist": { "value": 1 },
}
}`,
Migration: DeleteWhitelistKeys(),
ExpectedEnv: map[string]string{},
},
}
for tn, tc := range cases {
t.Run(tn, tc.Run)
}
}
func TestFullMigration(t *testing.T) {
cases := map[string]MigrationTest{
"no-fail-on-empty-properties": {
TileProperties: `
{
"properties": {}
}`,
Migration: FullMigration(),
ExpectedEnv: map[string]string{},
},
}
for tn, tc := range cases {
t.Run(tn, tc.Run)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/client/broker-response.go | pkg/client/broker-response.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 client
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// BrokerResponse encodes an OSB HTTP response in a (technical) human and
// machine readable way.
type BrokerResponse struct {
// WARNING: BrokerResponse is exposed to users and automated tooling
// so DO NOT remove or rename fields unless strictly necessary.
// You MAY add new fields.
Error error `json:"error,omitempty"`
Url string `json:"url,omitempty"`
Method string `json:"http_method,omitempty"`
StatusCode int `json:"status_code,omitempty"`
ResponseBody json.RawMessage `json:"response,omitempty"`
}
func (br *BrokerResponse) UpdateError(err error) {
if br.Error == nil {
br.Error = err
}
}
func (br *BrokerResponse) UpdateRequest(req *http.Request) {
if req == nil {
return
}
br.Url = req.URL.String()
br.Method = req.Method
}
func (br *BrokerResponse) UpdateResponse(res *http.Response) {
if res == nil {
return
}
br.StatusCode = res.StatusCode
body, err := ioutil.ReadAll(res.Body)
if err != nil {
br.UpdateError(err)
} else {
br.ResponseBody = json.RawMessage(body)
}
}
func (br *BrokerResponse) InError() bool {
return br.Error != nil
}
func (br *BrokerResponse) String() string {
if br.InError() {
return fmt.Sprintf("%s %s -> %d, Error: %q)", br.Method, br.Url, br.StatusCode, br.Error)
}
return fmt.Sprintf("%s %s -> %d, %q", br.Method, br.Url, br.StatusCode, br.ResponseBody)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/client/client.go | pkg/client/client.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 client
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"github.com/pivotal-cf/brokerapi"
"github.com/spf13/viper"
)
const (
// ClientsBrokerApiVersion is the minimum supported version of the client.
// Note: This may need to be changed in the future as we use newer versions
// of the OSB API, but should be kept near the lower end of the systems we
// expect to be compatible with to ensure any reverse-compatibility measures
// put in place work.
ClientsBrokerApiVersion = "2.13"
)
// NewClientFromEnv creates a new client from the client configuration properties.
func NewClientFromEnv() (*Client, error) {
user := viper.GetString("api.user")
pass := viper.GetString("api.password")
port := viper.GetInt("api.port")
viper.SetDefault("api.hostname", "localhost")
host := viper.GetString("api.hostname")
return New(user, pass, host, port)
}
// New creates a new OSB Client connected to the given resource.
func New(username, password, hostname string, port int) (*Client, error) {
base := fmt.Sprintf("http://%s:%s@%s:%d/v2/", username, password, hostname, port)
baseUrl, err := url.Parse(base)
if err != nil {
return nil, err
}
return &Client{BaseUrl: baseUrl}, nil
}
type Client struct {
BaseUrl *url.URL
}
// Catalog fetches the service catalog
func (client *Client) Catalog() *BrokerResponse {
return client.makeRequest(http.MethodGet, "catalog", nil)
}
// Provision creates a new service with the given instanceId, of type serviceId,
// from the plan planId, with additional details provisioningDetails
func (client *Client) Provision(instanceId, serviceId, planId string, provisioningDetails json.RawMessage) *BrokerResponse {
url := fmt.Sprintf("service_instances/%s?accepts_incomplete=true", instanceId)
return client.makeRequest(http.MethodPut, url, brokerapi.ProvisionDetails{
ServiceID: serviceId,
PlanID: planId,
RawParameters: provisioningDetails,
})
}
// Deprovision destroys a service instance of type instanceId
func (client *Client) Deprovision(instanceId, serviceId, planId string) *BrokerResponse {
url := fmt.Sprintf("service_instances/%s?accepts_incomplete=true&service_id=%s&plan_id=%s", instanceId, serviceId, planId)
return client.makeRequest(http.MethodDelete, url, nil)
}
// Bind creates an account identified by bindingId and gives it access to instanceId
func (client *Client) Bind(instanceId, bindingId, serviceId, planId string, parameters json.RawMessage) *BrokerResponse {
url := fmt.Sprintf("service_instances/%s/service_bindings/%s", instanceId, bindingId)
return client.makeRequest(http.MethodPut, url, brokerapi.BindDetails{
ServiceID: serviceId,
PlanID: planId,
RawParameters: parameters,
})
}
// Unbind destroys an account identified by bindingId
func (client *Client) Unbind(instanceId, bindingId, serviceId, planId string) *BrokerResponse {
url := fmt.Sprintf("service_instances/%s/service_bindings/%s?service_id=%s&plan_id=%s", instanceId, bindingId, serviceId, planId)
return client.makeRequest(http.MethodDelete, url, nil)
}
// Update sends a patch request to change the plan
func (client *Client) Update(instanceId, serviceId, planId string, parameters json.RawMessage) *BrokerResponse {
url := fmt.Sprintf("service_instances/%s", instanceId)
return client.makeRequest(http.MethodPatch, url, brokerapi.UpdateDetails{
ServiceID: serviceId,
PlanID: planId,
RawParameters: parameters,
})
}
// LastOperation queries the status of a long-running job on the server
func (client *Client) LastOperation(instanceId string) *BrokerResponse {
url := fmt.Sprintf("service_instances/%s/last_operation", instanceId)
return client.makeRequest(http.MethodGet, url, nil)
}
func (client *Client) makeRequest(method, path string, body interface{}) *BrokerResponse {
br := BrokerResponse{}
req, err := client.newRequest(method, path, body)
br.UpdateRequest(req)
br.UpdateError(err)
if br.InError() {
return &br
}
resp, err := http.DefaultClient.Do(req)
br.UpdateResponse(resp)
br.UpdateError(err)
return &br
}
func (client *Client) newRequest(method, path string, body interface{}) (*http.Request, error) {
url, err := client.BaseUrl.Parse(path)
if err != nil {
return nil, err
}
var buffer io.ReadWriter
if body != nil {
buffer = new(bytes.Buffer)
enc := json.NewEncoder(buffer)
enc.SetEscapeHTML(false)
err := enc.Encode(body)
if err != nil {
return nil, err
}
}
request, err := http.NewRequest(method, url.String(), buffer)
if err != nil {
return nil, err
}
request.Header.Set("X-Broker-Api-Version", ClientsBrokerApiVersion)
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
return request, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/client/example-runner_test.go | pkg/client/example-runner_test.go | package client
import (
"encoding/json"
"os"
"reflect"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
)
func ExampleGetAllCompleteServiceExamples_jsonSpec() {
allExamples := []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Basic Configuration",
Description: "Creates an account with the permission `clouddebugger.agent`.",
PlanId: "10866183-a775-49e8-96e3-4e7a901e4a79",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{}},
ServiceName: "google-stackdriver-debugger",
ServiceId: "83837945-1547-41e0-b661-ea31d76eed11",
ExpectedOutput: broker.CreateJsonSchema([]broker.BrokerVariable{
{
Required: true,
FieldName: "Email",
Type: "string",
Details: "Email address of the service account.",
},
}),
},
}
b, err := json.MarshalIndent(allExamples, "", "\t")
if err != nil {
panic(err)
}
os.Stdout.Write(b)
}
func TestGetExamplesForAService(t *testing.T) {
cases := map[string]struct {
ServiceDefinition *broker.ServiceDefinition
ExpectedResponse []CompleteServiceExample
ExpectedError error
}{
"service with no examples": {
ServiceDefinition: &broker.ServiceDefinition{
Id: "TestService",
},
ExpectedResponse: []CompleteServiceExample(nil),
ExpectedError: nil,
},
"google-stackdriver-debugger": {
ServiceDefinition: &broker.ServiceDefinition{
Id: "83837945-1547-41e0-b661-ea31d76eed11",
Name: "google-stackdriver-debugger",
BindOutputVariables: []broker.BrokerVariable{
{
Required: true,
FieldName: "Email",
Type: "string",
Details: "Email address of the service account.",
},
},
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Creates an account with the permission `clouddebugger.agent`.",
PlanId: "10866183-a775-49e8-96e3-4e7a901e4a79",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
},
},
ExpectedResponse: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Basic Configuration",
Description: "Creates an account with the permission `clouddebugger.agent`.",
PlanId: "10866183-a775-49e8-96e3-4e7a901e4a79",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{}},
ServiceName: "google-stackdriver-debugger",
ServiceId: "83837945-1547-41e0-b661-ea31d76eed11",
ExpectedOutput: broker.CreateJsonSchema([]broker.BrokerVariable{
{
Required: true,
FieldName: "Email",
Type: "string",
Details: "Email address of the service account.",
},
}),
},
},
ExpectedError: nil,
},
"google-dataflow": {
ServiceDefinition: &broker.ServiceDefinition{
Id: "3e897eb3-9062-4966-bd4f-85bda0f73b3d",
Name: "google-dataflow",
BindOutputVariables: []broker.BrokerVariable{
{
Required: true,
FieldName: "Email",
Type: "string",
Details: "Email address of the service account.",
},
{
Required: true,
FieldName: "Name",
Type: "string",
Details: "The name of the service account.",
},
},
Examples: []broker.ServiceExample{
{
Name: "Developer",
Description: "Creates a Dataflow user and grants it permission to create, drain and cancel jobs.",
PlanId: "8e956dd6-8c0f-470c-9a11-065537d81872",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
{
Name: "Viewer",
Description: "Creates a Dataflow user and grants it permission to create, drain and cancel jobs.",
PlanId: "8e956dd6-8c0f-470c-9a11-065537d81872",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{"role": "dataflow.viewer"},
},
},
},
ExpectedResponse: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Developer",
Description: "Creates a Dataflow user and grants it permission to create, drain and cancel jobs.",
PlanId: "8e956dd6-8c0f-470c-9a11-065537d81872",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
ServiceName: "google-dataflow",
ServiceId: "3e897eb3-9062-4966-bd4f-85bda0f73b3d",
ExpectedOutput: broker.CreateJsonSchema([]broker.BrokerVariable{
{
Required: true,
FieldName: "Email",
Type: "string",
Details: "Email address of the service account.",
},
{
Required: true,
FieldName: "Name",
Type: "string",
Details: "The name of the service account.",
},
}),
},
{
ServiceExample: broker.ServiceExample{
Name: "Viewer",
Description: "Creates a Dataflow user and grants it permission to create, drain and cancel jobs.",
PlanId: "8e956dd6-8c0f-470c-9a11-065537d81872",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{"role": "dataflow.viewer"},
},
ServiceName: "google-dataflow",
ServiceId: "3e897eb3-9062-4966-bd4f-85bda0f73b3d",
ExpectedOutput: broker.CreateJsonSchema([]broker.BrokerVariable{
{
Required: true,
FieldName: "Email",
Type: "string",
Details: "Email address of the service account.",
},
{
Required: true,
FieldName: "Name",
Type: "string",
Details: "The name of the service account.",
},
}),
},
},
ExpectedError: nil,
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual, err := GetExamplesForAService(tc.ServiceDefinition)
expectError(t, tc.ExpectedError, err)
if !reflect.DeepEqual(tc.ExpectedResponse, actual) {
t.Errorf("Expected: %v got %v", tc.ExpectedResponse, actual)
}
})
}
}
func expectError(t *testing.T, expected, actual error) {
t.Helper()
expectedErr := expected != nil
gotErr := actual != nil
switch {
case expectedErr && gotErr:
if expected.Error() != actual.Error() {
t.Fatalf("Expected: %v, got: %v", expected, actual)
}
case expectedErr && !gotErr:
t.Fatalf("Expected: %v, got: %v", expected, actual)
case !expectedErr && gotErr:
t.Fatalf("Expected no error but got: %v", actual)
}
}
func TestFilterMatchingServiceExamples(t *testing.T) {
cases := map[string]struct {
ServiceExamples []CompleteServiceExample
ServiceName string
ExampleName string
Response []CompleteServiceExample
}{
"No ServiceName or ExampleName specified.": {
ServiceExamples: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Foo",
},
ServiceName: "Service-Foo",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
},
ServiceName: "",
ExampleName: "",
Response: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Foo",
},
ServiceName: "Service-Foo",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
},
},
"ServiceName is specified, no ExampleName is specified. No matching CompleteServiceExample exists": {
ServiceExamples: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Foo",
},
ServiceName: "Service-Foo",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
},
ServiceName: "Service-Unicorn",
ExampleName: "",
Response: []CompleteServiceExample(nil),
},
"ServiceName is specified, no ExampleName is specified. Two matching CompleteServiceExample exist": {
ServiceExamples: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Foo",
},
ServiceName: "Service-Foo",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-FooBar",
},
ServiceName: "Service-Bar",
},
},
ServiceName: "Service-Bar",
ExampleName: "",
Response: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-FooBar",
},
ServiceName: "Service-Bar",
},
},
},
"Both ServiceName and ExampleName are provided, but no matching CompleteServiceExample exists.": {
ServiceExamples: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Foo",
},
ServiceName: "Service-Foo",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
},
ServiceName: "Service-Bar",
ExampleName: "Example-Hello",
Response: []CompleteServiceExample(nil),
},
"Both ServiceName and ExampleName are provided, one matching CompleteServiceExample exists.": {
ServiceExamples: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Foo",
},
ServiceName: "Service-Foo",
},
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
},
ServiceName: "Service-Bar",
ExampleName: "Example-Bar",
Response: []CompleteServiceExample{
{
ServiceExample: broker.ServiceExample{
Name: "Example-Bar",
},
ServiceName: "Service-Bar",
},
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := FilterMatchingServiceExamples(tc.ServiceExamples, tc.ServiceName, tc.ExampleName)
if !reflect.DeepEqual(tc.Response, actual) {
t.Errorf("Expected: %v got %v", tc.Response, actual)
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/client/example-runner.go | pkg/client/example-runner.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 client
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"time"
"github.com/pivotal-cf/brokerapi"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
)
// RunExamplesForService runs all the examples for a given service name against
// the service broker pointed to by client. All examples in the registry get run
// if serviceName is blank. If exampleName is non-blank then only the example
// with the given name is run.
func RunExamplesForService(allExamples []CompleteServiceExample, client *Client, serviceName, exampleName string) error {
rand.Seed(time.Now().UTC().UnixNano())
for _, completeServiceExample := range FilterMatchingServiceExamples(allExamples, serviceName, exampleName) {
if err := RunExample(client, completeServiceExample); err != nil {
return err
}
}
return nil
}
// RunExamplesFromFile reads a json-encoded list of CompleteServiceExamples.
// All examples in the list get run if serviceName is blank. If exampleName
// is non-blank then only the example with the given name is run.
func RunExamplesFromFile(client *Client, fileName, serviceName, exampleName string) error {
rand.Seed(time.Now().UTC().UnixNano())
jsonFile, err := os.Open(fileName)
if err != nil {
log.Fatalf("Error opening file: %v", err)
}
defer jsonFile.Close()
var allExamples []CompleteServiceExample
byteValue, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(byteValue, &allExamples)
for _, completeServiceExample := range FilterMatchingServiceExamples(allExamples, serviceName, exampleName) {
if err := RunExample(client, completeServiceExample); err != nil {
return err
}
}
return nil
}
type CompleteServiceExample struct {
broker.ServiceExample `json: ",inline"`
ServiceName string `json: "service_name"`
ServiceId string `json: "service_id"`
ExpectedOutput map[string]interface{} `json: "expected_output"`
}
func GetExamplesForAService(service *broker.ServiceDefinition) ([]CompleteServiceExample, error) {
var examples []CompleteServiceExample
for _, example := range service.Examples {
serviceCatalogEntry, err := service.CatalogEntry()
if err != nil {
return nil, err
}
var completeServiceExample = CompleteServiceExample{
ServiceExample: example,
ServiceId: serviceCatalogEntry.ID,
ServiceName: service.Name,
ExpectedOutput: broker.CreateJsonSchema(service.BindOutputVariables),
}
examples = append(examples, completeServiceExample)
}
return examples, nil
}
// Do not run example if:
// 1. The service name is specified and does not match the current example's ServiceName
// 2. The service name is specified and matches the current example's ServiceName, and the example name is specified and does not match the current example's ExampleName
func FilterMatchingServiceExamples(allExamples []CompleteServiceExample, serviceName, exampleName string) []CompleteServiceExample {
var matchingExamples []CompleteServiceExample
for _, completeServiceExample := range allExamples {
if (serviceName != "" && serviceName != completeServiceExample.ServiceName) || (exampleName != "" && exampleName != completeServiceExample.ServiceExample.Name) {
continue
}
matchingExamples = append(matchingExamples, completeServiceExample)
}
return matchingExamples
}
// RunExample runs a single example against the given service on the broker
// pointed to by client.
func RunExample(client *Client, serviceExample CompleteServiceExample) error {
executor, err := newExampleExecutor(client, serviceExample)
if err != nil {
return err
}
executor.LogTestInfo()
// Cleanup the test if it fails partway through
defer func() {
log.Println("Cleaning up the environment")
executor.Unbind()
executor.Deprovision()
}()
if err := executor.Provision(); err != nil {
return err
}
bindResponse, err := executor.Bind()
if err != nil {
return err
}
if err := executor.Unbind(); err != nil {
return err
}
if err := executor.Deprovision(); err != nil {
return err
}
// Check that the binding response has the same fields as expected
var binding brokerapi.Binding
err = json.Unmarshal(bindResponse, &binding)
if err != nil {
return err
}
credentialsEntry := binding.Credentials.(map[string]interface{})
if err := broker.ValidateVariablesAgainstSchema(credentialsEntry, serviceExample.ExpectedOutput); err != nil {
log.Printf("Error: results don't match JSON Schema: %v", err)
return err
}
return nil
}
func retry(timeout, period time.Duration, function func() (tryAgain bool, err error)) error {
to := time.After(timeout)
tick := time.Tick(period)
if tryAgain, err := function(); !tryAgain {
return err
}
// Keep trying until we're timed out or got a result or got an error
for {
select {
case <-to:
return errors.New("Timeout while waiting for result")
case <-tick:
tryAgain, err := function()
if !tryAgain {
return err
}
}
}
}
func pollUntilFinished(client *Client, instanceId string) error {
return retry(15*time.Minute, 15*time.Second, func() (bool, error) {
log.Println("Polling for async job")
resp := client.LastOperation(instanceId)
if resp.InError() {
return false, resp.Error
}
if resp.StatusCode != 200 {
log.Printf("Bad status code %d, needed 200", resp.StatusCode)
return true, nil
}
var responseBody map[string]string
err := json.Unmarshal(resp.ResponseBody, &responseBody)
if err != nil {
return false, err
}
state := responseBody["state"]
eq := state == string(brokerapi.Succeeded)
log.Printf("Last operation for %q was %q\n", instanceId, state)
return !eq, nil
})
}
func newExampleExecutor(client *Client, serviceExample CompleteServiceExample) (*exampleExecutor, error) {
provisionParams, err := json.Marshal(serviceExample.ServiceExample.ProvisionParams)
if err != nil {
return nil, err
}
bindParams, err := json.Marshal(serviceExample.ServiceExample.BindParams)
if err != nil {
return nil, err
}
testid := rand.Uint32()
return &exampleExecutor{
Name: fmt.Sprintf("%s/%s", serviceExample.ServiceName, serviceExample.ServiceExample.Name),
ServiceId: serviceExample.ServiceId,
PlanId: serviceExample.ServiceExample.PlanId,
InstanceId: fmt.Sprintf("ex%d", testid),
BindingId: fmt.Sprintf("ex%d", testid),
ProvisionParams: provisionParams,
BindParams: bindParams,
client: client,
}, nil
}
type exampleExecutor struct {
Name string
ServiceId string
PlanId string
InstanceId string
BindingId string
ProvisionParams json.RawMessage
BindParams json.RawMessage
client *Client
}
// Provision attempts to create a service instance from the example.
// Multiple calls to provision will attempt to create a resource with the same
// ServiceId and details.
// If the response is an async result, Provision will attempt to wait until
// the Provision is complete.
func (ee *exampleExecutor) Provision() error {
log.Printf("Provisioning %s\n", ee.Name)
resp := ee.client.Provision(ee.InstanceId, ee.ServiceId, ee.PlanId, ee.ProvisionParams)
log.Println(resp.String())
if resp.InError() {
return resp.Error
}
switch resp.StatusCode {
case 201:
return nil
case 202:
return ee.pollUntilFinished()
default:
return fmt.Errorf("Unexpected response code %d", resp.StatusCode)
}
}
func (ee *exampleExecutor) pollUntilFinished() error {
return pollUntilFinished(ee.client, ee.InstanceId)
}
// Deprovision destroys the instance created by a call to Provision.
func (ee *exampleExecutor) Deprovision() error {
log.Printf("Deprovisioning %s\n", ee.Name)
resp := ee.client.Deprovision(ee.InstanceId, ee.ServiceId, ee.PlanId)
log.Println(resp.String())
if resp.InError() {
return resp.Error
}
switch resp.StatusCode {
case 200:
return nil
case 202:
return ee.pollUntilFinished()
default:
return fmt.Errorf("Unexpected response code %d", resp.StatusCode)
}
}
// Unbind unbinds the exact binding created by a call to Bind.
func (ee *exampleExecutor) Unbind() error {
// XXX(josephlewis42) Due to some unknown reason, binding Postgres and MySQL
// don't wait for all operations to finish before returning even though it
// looks like they do so we can get 500 errors back the first few times we try
// to unbind. Issue #222 was opened to address this. In the meantime this
// is a hack to get around it that will still fail if the 500 errors truly
// occur because of a real, unrecoverable, server error.
return retry(15*time.Minute, 15*time.Second, func() (bool, error) {
log.Printf("Unbinding %s\n", ee.Name)
resp := ee.client.Unbind(ee.InstanceId, ee.BindingId, ee.ServiceId, ee.PlanId)
log.Println(resp.String())
if resp.InError() {
return false, resp.Error
}
if resp.StatusCode == 200 {
return false, nil
}
if resp.StatusCode == 500 {
return true, nil
}
return false, fmt.Errorf("Unexpected response code %d", resp.StatusCode)
})
}
// Bind executes the bind portion of the create, this can only be called
// once successfully as subsequent binds will attempt to create bindings with
// the same ID.
func (ee *exampleExecutor) Bind() (json.RawMessage, error) {
log.Printf("Binding %s\n", ee.Name)
resp := ee.client.Bind(ee.InstanceId, ee.BindingId, ee.ServiceId, ee.PlanId, ee.BindParams)
log.Println(resp.String())
if resp.InError() {
return nil, resp.Error
}
if resp.StatusCode == 201 {
return resp.ResponseBody, nil
}
return nil, fmt.Errorf("Unexpected response code %d", resp.StatusCode)
}
// LogTestInfo writes information about the running example and a manual backout
// strategy if the test dies part of the way through.
func (ee *exampleExecutor) LogTestInfo() {
log.Printf("Running Example: %s\n", ee.Name)
ips := fmt.Sprintf("--instanceid %q --planid %q --serviceid %q", ee.InstanceId, ee.PlanId, ee.ServiceId)
log.Printf("gcp-service-broker client provision %s --params %q\n", ips, ee.ProvisionParams)
log.Printf("gcp-service-broker client bind %s --bindingid %q --params %q\n", ips, ee.BindingId, ee.BindParams)
log.Printf("gcp-service-broker client unbind %s --bindingid %q\n", ips, ee.BindingId)
log.Printf("gcp-service-broker client deprovision %s\n", ips)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/fetch_test.go | pkg/brokerpak/fetch_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"testing"
getter "github.com/hashicorp/go-getter"
)
func TestDefaultGetters(t *testing.T) {
getters := defaultGetters()
// gcs SHOULD NOT be in there
for _, prefix := range []string{"gs", "gcs"} {
if getters[prefix] != nil {
t.Errorf("expected default getters not to contain %q", prefix)
}
}
for _, prefix := range []string{"http", "https", "git", "hg"} {
if getters[prefix] == nil {
t.Errorf("expected default getters not to contain %q", prefix)
}
}
}
func TestNewFileGetterClient(t *testing.T) {
source := "http://www.example.com/foo/bar/bazz"
dest := "/tmp/path/to/dest"
client := newFileGetterClient(source, dest)
if client.Src != source {
t.Errorf("Expected Src to be %q got %q", source, client.Src)
}
if client.Dst != dest {
t.Errorf("Expected Dst to be %q got %q", dest, client.Dst)
}
if client.Mode != getter.ClientModeFile {
t.Errorf("Expected Dst to be %q got %q", getter.ClientModeFile, client.Mode)
}
if client.Getters == nil {
t.Errorf("Expected getters to be set")
}
if client.Decompressors == nil {
t.Errorf("Expected decompressors to be set")
}
if len(client.Decompressors) != 0 {
t.Errorf("Expected decompressors to be empty")
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/manifest.go | pkg/brokerpak/manifest.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/stream"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/ziputil"
getter "github.com/hashicorp/go-getter"
)
const manifestName = "manifest.yml"
type Manifest struct {
// Package metadata
PackVersion int `yaml:"packversion"`
// User modifiable values
Name string `yaml:"name"`
Version string `yaml:"version"`
Metadata map[string]string `yaml:"metadata"`
Platforms []Platform `yaml:"platforms"`
TerraformResources []TerraformResource `yaml:"terraform_binaries"`
ServiceDefinitions []string `yaml:"service_definitions"`
Parameters []ManifestParameter `yaml:"parameters"`
}
var _ validation.Validatable = (*Manifest)(nil)
// Validate will run struct validation on the fields of this manifest.
func (m *Manifest) Validate() (errs *validation.FieldError) {
if m.PackVersion != 1 {
errs = errs.Also(validation.ErrInvalidValue(m.PackVersion, "packversion"))
}
errs = errs.Also(
validation.ErrIfBlank(m.Name, "name"),
validation.ErrIfBlank(m.Version, "version"),
)
// Platforms
if len(m.Platforms) == 0 {
errs = errs.Also(validation.ErrMissingField("platforms"))
}
for i, platform := range m.Platforms {
errs = errs.Also(platform.Validate().ViaFieldIndex("platforms", i))
}
// Terraform Resources
if len(m.TerraformResources) == 0 {
errs = errs.Also(validation.ErrMissingField("terraform_binaries"))
}
for i, resource := range m.TerraformResources {
errs = errs.Also(resource.Validate().ViaFieldIndex("terraform_binaries", i))
}
// Service Definitions
if len(m.ServiceDefinitions) == 0 {
errs = errs.Also(validation.ErrMissingField("service_definitions"))
}
// Params
for i, param := range m.Parameters {
errs = errs.Also(param.Validate().ViaFieldIndex("parameters", i))
}
return errs
}
// AppliesToCurrentPlatform returns true if the one of the platforms in the
// manifest match the current GOOS and GOARCH.
func (m *Manifest) AppliesToCurrentPlatform() bool {
for _, platform := range m.Platforms {
if platform.MatchesCurrent() {
return true
}
}
return false
}
// Pack creates a brokerpak from the manifest and definitions.
func (m *Manifest) Pack(base, dest string) error {
// NOTE: we use "log" rather than Lager because this is used by the CLI and
// needs to be human readable rather than JSON.
log.Println("Packing...")
dir, err := ioutil.TempDir("", "brokerpak")
if err != nil {
return err
}
defer os.RemoveAll(dir) // clean up
log.Println("Using temp directory:", dir)
log.Println("Packing sources...")
if err := m.packSources(dir); err != nil {
return err
}
log.Println("Packing binaries...")
if err := m.packBinaries(dir); err != nil {
return err
}
log.Println("Packing definitions...")
if err := m.packDefinitions(dir, base); err != nil {
return err
}
log.Println("Creating archive:", dest)
return ziputil.Archive(dir, dest)
}
func (m *Manifest) packSources(tmp string) error {
for _, resource := range m.TerraformResources {
destination := filepath.Join(tmp, "src", resource.Name+".zip")
log.Println("\t", resource.Source, "->", destination)
if err := fetchArchive(resource.Source, destination); err != nil {
return err
}
}
return nil
}
func (m *Manifest) packBinaries(tmp string) error {
for _, platform := range m.Platforms {
platformPath := filepath.Join(tmp, "bin", platform.Os, platform.Arch)
for _, resource := range m.TerraformResources {
log.Println("\t", resource.Url(platform), "->", platformPath)
if err := getter.GetAny(platformPath, resource.Url(platform)); err != nil {
return err
}
}
}
return nil
}
func (m *Manifest) packDefinitions(tmp, base string) error {
// users can place definitions in any directory structure they like, even
// above the current directory so we standardize their location and names
// for the zip to avoid collisions
manifestCopy := *m
var servicePaths []string
for i, sd := range m.ServiceDefinitions {
defn := &tf.TfServiceDefinitionV1{}
if err := stream.Copy(stream.FromFile(base, sd), stream.ToYaml(defn)); err != nil {
return fmt.Errorf("couldn't parse %s: %v", sd, err)
}
packedName := fmt.Sprintf("service%d-%s.yml", i, defn.Name)
log.Printf("\t%s/%s -> %s/definitions/%s\n", base, sd, tmp, packedName)
if err := stream.Copy(stream.FromFile(base, sd), stream.ToFile(tmp, "definitions", packedName)); err != nil {
return err
}
servicePaths = append(servicePaths, "definitions/"+packedName)
}
manifestCopy.ServiceDefinitions = servicePaths
return stream.Copy(stream.FromYaml(manifestCopy), stream.ToFile(tmp, manifestName))
}
// ManifestParameter holds environment variables that will be looked up and
// passed to the executed Terraform instance.
type ManifestParameter struct {
// NOTE: Future fields should take inspiration from the CNAB spec because they
// solve a similar problem. https://github.com/deislabs/cnab-spec
Name string `yaml:"name"`
Description string `yaml:"description"`
}
var _ validation.Validatable = (*ManifestParameter)(nil)
// Validate implements validation.Validatable.
func (param *ManifestParameter) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(param.Name, "name"),
validation.ErrIfBlank(param.Description, "description"),
)
}
// NewExampleManifest creates a new manifest with sample values for the service broker suitable for giving a user a template to manually edit.
func NewExampleManifest() Manifest {
return Manifest{
PackVersion: 1,
Name: "my-services-pack",
Version: "1.0.0",
Metadata: map[string]string{
"author": "me@example.com",
},
Platforms: []Platform{
{Os: "linux", Arch: "386"},
{Os: "linux", Arch: "amd64"},
},
TerraformResources: []TerraformResource{
{
Name: "terraform",
Version: "0.11.9",
Source: "https://github.com/hashicorp/terraform/archive/v0.11.9.zip",
},
{
Name: "terraform-provider-google-beta",
Version: "1.19.0",
Source: "https://github.com/terraform-providers/terraform-provider-google/archive/v1.19.0.zip",
},
},
ServiceDefinitions: []string{"example-service-definition.yml"},
Parameters: []ManifestParameter{
{Name: "MY_ENVIRONMENT_VARIABLE", Description: "Set this to whatever you like."},
},
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/cmd_test.go | pkg/brokerpak/cmd_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/stream"
)
func fakeBrokerpak() (string, error) {
dir, err := ioutil.TempDir("", "fakepak")
if err != nil {
return "", err
}
defer os.RemoveAll(dir)
tfSrc := filepath.Join(dir, "terraform")
if err := stream.Copy(stream.FromString("dummy-file"), stream.ToFile(tfSrc)); err != nil {
return "", err
}
exampleManifest := &Manifest{
PackVersion: 1,
Name: "my-services-pack",
Version: "1.0.0",
Metadata: map[string]string{
"author": "me@example.com",
},
Platforms: []Platform{
{Os: "linux", Arch: "386"},
{Os: "linux", Arch: "amd64"},
},
// These resources are stubbed with a local dummy file
TerraformResources: []TerraformResource{
{
Name: "terraform",
Version: "0.11.9",
Source: tfSrc,
UrlTemplate: tfSrc,
},
{
Name: "terraform-provider-google-beta",
Version: "1.19.0",
Source: tfSrc,
UrlTemplate: tfSrc,
},
},
ServiceDefinitions: []string{"example-service-definition.yml"},
Parameters: []ManifestParameter{
{Name: "TEST_PARAM", Description: "An example paramater that will be injected into Terraform's environment variables."},
},
}
if err := stream.Copy(stream.FromYaml(exampleManifest), stream.ToFile(dir, manifestName)); err != nil {
return "", err
}
for _, path := range exampleManifest.ServiceDefinitions {
if err := stream.Copy(stream.FromYaml(tf.NewExampleTfServiceDefinition()), stream.ToFile(dir, path)); err != nil {
return "", err
}
}
return Pack(dir)
}
func ExampleValidate() {
pk, err := fakeBrokerpak()
defer os.Remove(pk)
if err != nil {
panic(err)
}
if err := Validate(pk); err != nil {
panic(err)
} else {
fmt.Println("ok!")
}
// Output: ok!
}
func TestFinfo(t *testing.T) {
pk, err := fakeBrokerpak()
defer os.Remove(pk)
if err != nil {
t.Fatal(err)
}
buf := &bytes.Buffer{}
if err := finfo(pk, buf); err != nil {
t.Fatal(err)
}
// Check for "important strings" which MUST exist for this to be a valid
// output
importantStrings := []string{
"Information", // heading
"my-services-pack", // name
"1.0.0", // version
"Parameters", // heading
"TEST_PARAM", // value
"Dependencies", // heading
"terraform", // dependency
"terraform-provider-google-beta", // dependency
"Services", // heading
"00000000-0000-0000-0000-000000000000", // guid
"example-service", // name
"Contents", // heading
"bin/", // directory
"definitions/", // directory
"manifest.yml", // manifest
"src/terraform-provider-google-beta.zip", // file
"src/terraform.zip", // file
}
actual := string(buf.Bytes())
for _, str := range importantStrings {
if !strings.Contains(actual, str) {
fmt.Errorf("Expected output to contain %s but it didn't", str)
}
}
}
func TestRegistryFromLocalBrokerpak(t *testing.T) {
pk, err := fakeBrokerpak()
defer os.Remove(pk)
if err != nil {
t.Fatal(err)
}
abs, err := filepath.Abs(pk)
if err != nil {
t.Fatal(err)
}
registry, err := registryFromLocalBrokerpak(abs)
if err != nil {
t.Fatal(err)
}
if len(registry) != 1 {
t.Fatalf("Expected %d services but got %d", 1, len(registry))
}
svc, err := registry.GetServiceById("00000000-0000-0000-0000-000000000000")
if err != nil {
t.Fatal(err)
}
if svc.Name != "example-service" {
t.Errorf("Expected exapmle-service, got %q", svc.Name)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/platform_test.go | pkg/brokerpak/platform_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"errors"
"fmt"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
func ExamplePlatform_String() {
p := Platform{Os: "bsd", Arch: "amd64"}
fmt.Println(p.String())
// Output: bsd/amd64
}
func ExamplePlatform_Equals() {
p := Platform{Os: "beos", Arch: "webasm"}
fmt.Println(p.Equals(p))
fmt.Println(p.Equals(CurrentPlatform()))
// Output: true
// false
}
func ExamplePlatform_MatchesCurrent() {
fmt.Println(CurrentPlatform().MatchesCurrent())
// Output: true
}
func TestPlatform_Validate(t *testing.T) {
cases := map[string]validation.ValidatableTest{
"blank obj": {
Object: &Platform{},
Expect: errors.New("missing field(s): arch, os"),
},
"good obj": {
Object: &Platform{
Os: "linux",
Arch: "amd64",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
tc.Assert(t)
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/manifest_test.go | pkg/brokerpak/manifest_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"errors"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
func TestNewExampleManifest(t *testing.T) {
exampleManifest := NewExampleManifest()
if err := exampleManifest.Validate(); err != nil {
t.Fatalf("example manifest should be valid, but got error: %v", err)
}
}
func TestManifestParameter_Validate(t *testing.T) {
cases := map[string]validation.ValidatableTest{
"blank obj": {
Object: &ManifestParameter{},
Expect: errors.New("missing field(s): description, name"),
},
"good obj": {
Object: &ManifestParameter{
Name: "TEST",
Description: "Usage goes here",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
tc.Assert(t)
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/config.go | pkg/brokerpak/config.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/toggles"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/spf13/viper"
)
const (
// BuiltinPakLocation is the file-system location to load brokerpaks from to
// make them look builtin.
BuiltinPakLocation = "/usr/share/gcp-service-broker/builtin-brokerpaks"
brokerpakSourcesKey = "brokerpak.sources"
brokerpakConfigKey = "brokerpak.config"
brokerpakBuiltinPathKey = "brokerpak.builtin.path"
)
var loadBuiltinToggle = toggles.Features.Toggle("enable-builtin-brokerpaks", true, `Load brokerpaks that are built-in to the software.`)
func init() {
viper.SetDefault(brokerpakSourcesKey, "{}")
viper.SetDefault(brokerpakConfigKey, "{}")
viper.SetDefault(brokerpakBuiltinPathKey, BuiltinPakLocation)
}
// BrokerpakSourceConfig represents a single configuration of a brokerpak.
type BrokerpakSourceConfig struct {
// BrokerpakUri holds the URI for loading the Brokerpak.
BrokerpakUri string `json:"uri"`
// ServicePrefix holds an optional prefix that will be prepended to every service name.
ServicePrefix string `json:"service_prefix"`
// ExcludedServices holds a newline delimited list of service UUIDs that will be excluded at registration time.
ExcludedServices string `json:"excluded_services"`
// Config holds the configuration options for the Brokerpak as a JSON object.
Config string `json:"config"`
// Notes holds user-defined notes about the Brokerpak and shouldn't be used programatically.
Notes string `json:"notes"`
}
var _ validation.Validatable = (*BrokerpakSourceConfig)(nil)
// Validate implements validation.Validatable.
func (b *BrokerpakSourceConfig) Validate() (errs *validation.FieldError) {
errs = errs.Also(validation.ErrIfBlank(b.BrokerpakUri, "uri"))
if b.ServicePrefix != "" {
errs = errs.Also(validation.ErrIfNotOSBName(b.ServicePrefix, "service_prefix"))
}
errs = errs.Also(validation.ErrIfNotJSON(json.RawMessage(b.Config), "config"))
return errs
}
// ExcludedServicesSlice gets the ExcludedServices as a slice of UUIDs.
func (b *BrokerpakSourceConfig) ExcludedServicesSlice() []string {
return utils.SplitNewlineDelimitedList(b.ExcludedServices)
}
// SetExcludedServices sets the ExcludedServices from a slice of UUIDs.
func (b *BrokerpakSourceConfig) SetExcludedServices(services []string) {
b.ExcludedServices = strings.Join(services, "\n")
}
// NewBrokerpakSourceConfigFromPath creates a new BrokerpakSourceConfig from a path.
func NewBrokerpakSourceConfigFromPath(path string) BrokerpakSourceConfig {
return BrokerpakSourceConfig{
BrokerpakUri: path,
Config: "{}",
}
}
// ServerConfig holds the Brokerpak configuration for the server.
type ServerConfig struct {
// Config holds global configuration options for the Brokerpak as a JSON object.
Config string
// Brokerpaks holds list of brokerpaks to load.
Brokerpaks map[string]BrokerpakSourceConfig
}
var _ validation.Validatable = (*ServerConfig)(nil)
// Validate returns an error if the configuration is invalid.
func (cfg *ServerConfig) Validate() (errs *validation.FieldError) {
errs = errs.Also(validation.ErrIfNotJSON(json.RawMessage(cfg.Config), "Config"))
for k, v := range cfg.Brokerpaks {
errs = errs.Also(validation.ErrIfNotOSBName(k, "").ViaFieldKey("Brokerpaks", k))
errs = errs.Also(v.Validate().ViaFieldKey("Brokerpaks", k))
}
return errs
}
// NewServerConfigFromEnv loads the global Brokerpak config from Viper.
func NewServerConfigFromEnv() (*ServerConfig, error) {
paks := map[string]BrokerpakSourceConfig{}
sources := viper.GetString(brokerpakSourcesKey)
if err := json.Unmarshal([]byte(sources), &paks); err != nil {
return nil, fmt.Errorf("couldn't deserialize brokerpak source config: %v", err)
}
cfg := ServerConfig{
Config: viper.GetString(brokerpakConfigKey),
Brokerpaks: paks,
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("brokerpak config was invalid: %v", err)
}
// Builtin paks fail validation because they reference the local filesystem
// but do work.
if loadBuiltinToggle.IsActive() {
log.Println("loading builtin brokerpaks")
paks, err := ListBrokerpaks(viper.GetString(brokerpakBuiltinPathKey))
if err != nil {
return nil, fmt.Errorf("couldn't load builtin brokerpaks: %v", err)
}
for i, path := range paks {
key := fmt.Sprintf("builtin-%d", i)
config := NewBrokerpakSourceConfigFromPath(path)
config.Notes = fmt.Sprintf("This pak was automatically loaded because the toggle %s was enabled", loadBuiltinToggle.EnvironmentVariable())
cfg.Brokerpaks[key] = config
}
}
return &cfg, nil
}
// ListBrokerpaks gets all brokerpaks in a given directory.
func ListBrokerpaks(directory string) ([]string, error) {
var paks []string
err := filepath.Walk(filepath.FromSlash(directory), func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if filepath.Ext(path) == ".brokerpak" {
paks = append(paks, path)
}
return nil
})
sort.Strings(paks)
if os.IsNotExist(err) {
return paks, nil
}
return paks, err
}
func newLocalFileServerConfig(path string) *ServerConfig {
return &ServerConfig{
Config: viper.GetString(brokerpakConfigKey),
Brokerpaks: map[string]BrokerpakSourceConfig{
"local-brokerpak": NewBrokerpakSourceConfigFromPath(path),
},
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/reader.go | pkg/brokerpak/reader.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"archive/zip"
"fmt"
"io/ioutil"
"path/filepath"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/stream"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/ziputil"
)
// BrokerPakReader reads bundled together Terraform and service definitions.
type BrokerPakReader struct {
contents *zip.ReadCloser
}
func (pak *BrokerPakReader) readYaml(name string, v interface{}) error {
fd := ziputil.Find(&pak.contents.Reader, name)
if fd == nil {
return fmt.Errorf("couldn't find the file with the name %q", name)
}
return stream.Copy(stream.FromReadCloserError(fd.Open()), stream.ToYaml(v))
}
// Manifest fetches the manifest out of the package.
func (pak *BrokerPakReader) Manifest() (*Manifest, error) {
manifest := &Manifest{}
if err := pak.readYaml(manifestName, manifest); err != nil {
return nil, err
}
return manifest, nil
}
// Services gets the list of services included in the pack.
func (pak *BrokerPakReader) Services() ([]tf.TfServiceDefinitionV1, error) {
manifest, err := pak.Manifest()
if err != nil {
return nil, err
}
var services []tf.TfServiceDefinitionV1
for _, serviceDefinition := range manifest.ServiceDefinitions {
tmp := tf.TfServiceDefinitionV1{}
if err := pak.readYaml(serviceDefinition, &tmp); err != nil {
return nil, err
}
services = append(services, tmp)
}
return services, nil
}
// Validate checks the manifest and service definitions for syntactic and
// limited semantic errors.
func (pak *BrokerPakReader) Validate() error {
manifest, err := pak.Manifest()
if err != nil {
return fmt.Errorf("couldn't open brokerpak manifest: %v", err)
}
if err := manifest.Validate(); err != nil {
return fmt.Errorf("couldn't validate brokerpak manifest: %v", err)
}
services, err := pak.Services()
if err != nil {
return fmt.Errorf("couldn't list services: %v", err)
}
for _, svc := range services {
if err := svc.Validate(); err != nil {
return fmt.Errorf("service %q failed validation: %v", svc.Name, err)
}
}
return nil
}
// Close closes the underlying reader for the BrokerPakReader.
func (pak *BrokerPakReader) Close() error {
return pak.contents.Close()
}
// ExtractPlatformBins extracts the binaries for the current platform to the
// given destination.
func (pak *BrokerPakReader) ExtractPlatformBins(destination string) error {
mf, err := pak.Manifest()
if err != nil {
return err
}
curr := CurrentPlatform()
if !mf.AppliesToCurrentPlatform() {
return fmt.Errorf("the package %q doesn't contain binaries compatible with the current platform %q", mf.Name, curr.String())
}
bindir := ziputil.Join("bin", curr.Os, curr.Arch)
return ziputil.Extract(&pak.contents.Reader, bindir, destination)
}
// Opens the file at the given path as a BrokerPakReader.
func OpenBrokerPak(pakPath string) (*BrokerPakReader, error) {
rc, err := zip.OpenReader(pakPath)
if err != nil {
return nil, err
}
return &BrokerPakReader{contents: rc}, nil
}
// DownloadAndOpenBrokerpak downloads a (potentially remote) brokerpak to
// the local filesystem and opens it.
func DownloadAndOpenBrokerpak(pakUri string) (*BrokerPakReader, error) {
// create a temp directory to hold the pak
pakDir, err := ioutil.TempDir("", "brokerpak-staging")
if err != nil {
return nil, fmt.Errorf("couldn't create brokerpak staging area for %q: %v", pakUri, err)
}
// Download the brokerpak
localLocation := filepath.Join(pakDir, "pack.brokerpak")
if err := fetchBrokerpak(pakUri, localLocation); err != nil {
return nil, fmt.Errorf("couldn't download brokerpak %q: %v", pakUri, err)
}
return OpenBrokerPak(localLocation)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/tf_resource.go | pkg/brokerpak/tf_resource.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"strings"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
// HashicorpUrlTemplate holds the default template for Hashicorp's terraform binary archive downloads.
const HashicorpUrlTemplate = "https://releases.hashicorp.com/${name}/${version}/${name}_${version}_${os}_${arch}.zip"
// TerraformResource represents a downloadable binary dependency (Terraform
// version or Provider).
type TerraformResource struct {
// Name holds the name of this resource. e.g. terraform-provider-google-beta
Name string `yaml:"name"`
// Version holds the version of the resource e.g. 1.19.0
Version string `yaml:"version"`
// Source holds the URI of an archive that contains the source code for this release.
Source string `yaml:"source"`
// UrlTemplate holds a custom URL template to get the release of the given tool.
// Paramaters available are ${name}, ${version}, ${os}, and ${arch}.
// If non is specified HashicorpUrlTemplate is used.
UrlTemplate string `yaml:"url_template,omitempty"`
}
var _ validation.Validatable = (*TerraformResource)(nil)
// Validate implements validation.Validatable.
func (tr *TerraformResource) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(tr.Name, "name"),
validation.ErrIfBlank(tr.Version, "version"),
validation.ErrIfBlank(tr.Source, "source"),
)
}
// Url constructs a download URL based on a platform.
func (tr *TerraformResource) Url(platform Platform) string {
replacer := strings.NewReplacer("${name}", tr.Name, "${version}", tr.Version, "${os}", platform.Os, "${arch}", platform.Arch)
url := tr.UrlTemplate
if url == "" {
url = HashicorpUrlTemplate
}
return replacer.Replace(url)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/registrar_test.go | pkg/brokerpak/registrar_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"errors"
"os"
"os/exec"
"path/filepath"
"reflect"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
)
func TestNewRegistrar(t *testing.T) {
// Create a dummy brokerpak
pk, err := fakeBrokerpak()
if err != nil {
t.Fatal(err)
}
defer os.Remove(pk)
abs, err := filepath.Abs(pk)
if err != nil {
t.Fatal(err)
}
config := newLocalFileServerConfig(abs)
registry := broker.BrokerRegistry{}
err = NewRegistrar(config).Register(registry)
if err != nil {
t.Fatal(err)
}
if len(registry) != 1 {
t.Fatal("Expected length to be 1 got", len(registry))
}
}
func TestRegistrar_toDefinitions(t *testing.T) {
nopExecutor := func(c *exec.Cmd) error {
return nil
}
fakeDefn := func(name, id string) tf.TfServiceDefinitionV1 {
ex := tf.NewExampleTfServiceDefinition()
ex.Id = id
ex.Name = "service-" + name
return ex
}
goodCases := map[string]struct {
Services []tf.TfServiceDefinitionV1
Config BrokerpakSourceConfig
ExpectedNames []string
}{
"straight though": {
Services: []tf.TfServiceDefinitionV1{
fakeDefn("foo", "b69a96ad-0c38-4e84-84a3-be9513e3c645"),
fakeDefn("bar", "f71f1327-2bce-41b4-a833-0ec6430dd7ca"),
},
Config: BrokerpakSourceConfig{
ExcludedServices: "",
ServicePrefix: "",
},
ExpectedNames: []string{"service-foo", "service-bar"},
},
"prefix": {
Services: []tf.TfServiceDefinitionV1{
fakeDefn("foo", "b69a96ad-0c38-4e84-84a3-be9513e3c645"),
fakeDefn("bar", "f71f1327-2bce-41b4-a833-0ec6430dd7ca"),
},
Config: BrokerpakSourceConfig{
ExcludedServices: "",
ServicePrefix: "pre-",
},
ExpectedNames: []string{"pre-service-foo", "pre-service-bar"},
},
"exclude-foo": {
Services: []tf.TfServiceDefinitionV1{
fakeDefn("foo", "b69a96ad-0c38-4e84-84a3-be9513e3c645"),
fakeDefn("bar", "f71f1327-2bce-41b4-a833-0ec6430dd7ca"),
},
Config: BrokerpakSourceConfig{
ExcludedServices: "b69a96ad-0c38-4e84-84a3-be9513e3c645",
ServicePrefix: "",
},
ExpectedNames: []string{"service-bar"},
},
}
for tn, tc := range goodCases {
t.Run(tn, func(t *testing.T) {
r := NewRegistrar(nil)
defns, err := r.toDefinitions(tc.Services, tc.Config, nopExecutor)
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
var actualNames []string
for _, defn := range defns {
actualNames = append(actualNames, defn.Name)
}
if !reflect.DeepEqual(actualNames, tc.ExpectedNames) {
t.Errorf("Expected names to be %v, got %v", tc.ExpectedNames, actualNames)
}
})
}
badCases := map[string]struct {
Services []tf.TfServiceDefinitionV1
Config BrokerpakSourceConfig
ExpectedError string
}{
"bad service": {
Services: []tf.TfServiceDefinitionV1{
fakeDefn("foo", "bad uuid"),
},
Config: BrokerpakSourceConfig{},
ExpectedError: "field must be a UUID: id",
},
}
for tn, tc := range badCases {
t.Run(tn, func(t *testing.T) {
r := NewRegistrar(nil)
defns, err := r.toDefinitions(tc.Services, tc.Config, nopExecutor)
if err == nil {
t.Fatal("Expected error, got: <nil>")
}
if defns != nil {
t.Errorf("Expected defns to be nil got %v", defns)
}
if err.Error() != tc.ExpectedError {
t.Errorf("Expected error to be %q got %v", tc.ExpectedError, err)
}
})
}
}
func TestRegistrar_resolveParameters(t *testing.T) {
r := NewRegistrar(nil)
cases := map[string]struct {
Context map[string]interface{}
Params []ManifestParameter
Expected map[string]string
}{
"no-params": {
Context: map[string]interface{}{"n": 1, "s": "two", "b": true},
Params: []ManifestParameter{},
Expected: map[string]string{},
},
"missing-in-context": {
Context: map[string]interface{}{"n": 1, "s": "two", "b": true},
Params: []ManifestParameter{
{Name: "foo", Description: "some missing param"},
},
Expected: map[string]string{},
},
"contained-in-context": {
Context: map[string]interface{}{"n": 1, "s": "two", "b": true},
Params: []ManifestParameter{
{Name: "s", Description: "a string param"},
{Name: "b", Description: "a bool param"},
{Name: "n", Description: "a numeric param"},
},
Expected: map[string]string{"s": "two", "b": "true", "n": "1"},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
vc, err := varcontext.Builder().MergeMap(tc.Context).Build()
if err != nil {
t.Fatal(err)
}
actual := r.resolveParameters(tc.Params, vc)
if !reflect.DeepEqual(actual, tc.Expected) {
t.Errorf("Expected params to be: %v got %v", tc.Expected, actual)
}
})
}
}
func TestRegistrar_walk(t *testing.T) {
goodCases := map[string]struct {
Config *ServerConfig
Expected map[string]map[string]interface{}
}{
"basic": {
Config: &ServerConfig{
Config: `{}`,
Brokerpaks: map[string]BrokerpakSourceConfig{
"example": {Config: `{}`},
},
},
Expected: map[string]map[string]interface{}{
"example": map[string]interface{}{},
},
},
"server-config": {
Config: &ServerConfig{
Config: `{"foo":"bar"}`,
Brokerpaks: map[string]BrokerpakSourceConfig{
"example": {Config: `{}`},
},
},
Expected: map[string]map[string]interface{}{
"example": map[string]interface{}{"foo": "bar"},
},
},
"override": {
Config: &ServerConfig{
Config: `{"foo":"bar"}`,
Brokerpaks: map[string]BrokerpakSourceConfig{
"example": {Config: `{"foo":"bazz"}`},
},
},
Expected: map[string]map[string]interface{}{
"example": map[string]interface{}{"foo": "bazz"},
},
},
"additive configs": {
Config: &ServerConfig{
Config: `{"foo":"bar"}`,
Brokerpaks: map[string]BrokerpakSourceConfig{
"example": {Config: `{"bar":"bazz"}`},
},
},
Expected: map[string]map[string]interface{}{
"example": map[string]interface{}{"foo": "bar", "bar": "bazz"},
},
},
}
for tn, tc := range goodCases {
t.Run(tn, func(t *testing.T) {
actual := make(map[string]map[string]interface{})
err := NewRegistrar(tc.Config).walk(func(name string, pak BrokerpakSourceConfig, vc *varcontext.VarContext) error {
actual[name] = vc.ToMap()
return nil
})
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
if !reflect.DeepEqual(tc.Expected, actual) {
t.Errorf("Expected %v got %v", tc.Expected, actual)
}
})
}
badCases := map[string]struct {
Config *ServerConfig
Expected string
}{
"bad global config": {
Config: &ServerConfig{
Config: `a`,
Brokerpaks: map[string]BrokerpakSourceConfig{
"example": {Config: `{}`},
},
},
Expected: "couldn't merge config for brokerpak \"example\": 1 error(s) occurred: invalid character 'a' looking for beginning of value",
},
"bad local config": {
Config: &ServerConfig{
Config: `{}`,
Brokerpaks: map[string]BrokerpakSourceConfig{
"example": {Config: `b`},
},
},
Expected: "couldn't merge config for brokerpak \"example\": 1 error(s) occurred: invalid character 'b' looking for beginning of value",
},
"walk error": {
Config: &ServerConfig{
Config: `{}`,
Brokerpaks: map[string]BrokerpakSourceConfig{
"example": {Config: `{}`},
},
},
Expected: "walk raised error",
},
}
for tn, tc := range badCases {
t.Run(tn, func(t *testing.T) {
err := NewRegistrar(tc.Config).walk(func(name string, pak BrokerpakSourceConfig, vc *varcontext.VarContext) error {
return errors.New("walk raised error")
})
if err == nil {
t.Fatalf("Expected error %q, got: nil", tc.Expected)
}
if tc.Expected != err.Error() {
t.Errorf("Expected: %q got: %q", tc.Expected, err.Error())
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/fetch.go | pkg/brokerpak/fetch.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"cloud.google.com/go/storage"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/stream"
getter "github.com/hashicorp/go-getter"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
// fetchArchive uses go-getter to download archives. By default go-getter
// decompresses archives, so this configuration prevents that.
func fetchArchive(src, dest string) error {
return newFileGetterClient(src, dest).Get()
}
// fetchBrokerpak downloads a local or remote brokerpak; brokerpaks can be
// fetched remotely using the gs:// prefix which will load them from a
// Cloud Storage bucket with the broker's credentials.
// Relative paths are resolved relative to the executable.
func fetchBrokerpak(src, dest string) error {
execWd := filepath.Dir(os.Args[0])
execDir, err := filepath.Abs(execWd)
if err != nil {
return fmt.Errorf("couldn't turn dir %q into abs path: %v", execWd, err)
}
client := newFileGetterClient(src, dest)
client.Getters["gs"] = &gsGetter{}
client.Pwd = execDir
return client.Get()
}
func defaultGetters() map[string]getter.Getter {
getters := map[string]getter.Getter{}
for k, g := range getter.Getters {
getters[k] = g
}
return getters
}
// newFileGetterClient creates a new client that will fetch a single file,
// with the default set of getters and will NOT automatically decompress it.
func newFileGetterClient(src, dest string) *getter.Client {
return &getter.Client{
Src: src,
Dst: dest,
Mode: getter.ClientModeFile,
Getters: defaultGetters(),
Decompressors: map[string]getter.Decompressor{},
}
}
// gsGetter is a go-getter that works on Cloud Storage using the broker's
// service account. It's incomplete in that it doesn't support directories.
type gsGetter struct{}
// ClientMode is unsupported for gsGetter.
func (g *gsGetter) ClientMode(u *url.URL) (getter.ClientMode, error) {
return getter.ClientModeInvalid, errors.New("mode is not supported for this client")
}
// Get clones a remote destination to a local directory.
func (g *gsGetter) Get(dst string, u *url.URL) error {
return errors.New("getting directories is not supported for this client")
}
// GetFile downloads the give URL into the given path. The URL must
// reference a single file. If possible, the Getter should check if
// the remote end contains the same file and no-op this operation.
func (g *gsGetter) GetFile(dst string, u *url.URL) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client, err := g.client(ctx)
if err != nil {
return err
}
reader, err := g.objectAt(client, u).NewReader(ctx)
if err != nil {
return fmt.Errorf("couldn't open object at %q: %v", u.String(), err)
}
return stream.Copy(stream.FromReadCloser(reader), stream.ToFile(dst))
}
func (gsGetter) objectAt(client *storage.Client, u *url.URL) *storage.ObjectHandle {
return client.Bucket(u.Hostname()).Object(strings.TrimPrefix(u.Path, "/"))
}
func (gsGetter) client(ctx context.Context) (*storage.Client, error) {
creds, err := google.CredentialsFromJSON(ctx, []byte(utils.GetServiceAccountJson()), storage.ScopeReadOnly)
if err != nil {
return nil, errors.New("couldn't get JSON credentials from the enviornment")
}
client, err := storage.NewClient(ctx, option.WithCredentials(creds), option.WithUserAgent(utils.CustomUserAgent))
if err != nil {
return nil, fmt.Errorf("couldn't connect to Cloud Storage: %v", err)
}
return client, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/config_test.go | pkg/brokerpak/config_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"fmt"
"reflect"
"testing"
"github.com/spf13/viper"
)
func TestNewBrokerpakSourceConfigFromPath(t *testing.T) {
t.Run("is-valid-by-default", func(t *testing.T) {
cfg := NewBrokerpakSourceConfigFromPath("/path/to/my/pak.brokerpak")
if err := cfg.Validate(); err != nil {
t.Fatalf("Expected no error got %v", err)
}
})
t.Run("has-empty-config-by-default", func(t *testing.T) {
cfg := NewBrokerpakSourceConfigFromPath("/path/to/my/pak.brokerpak")
if cfg.Config != "{}" {
t.Fatalf("Expected empty config '{}' got %q", cfg.Config)
}
})
t.Run("has-no-excluded-services-by-default", func(t *testing.T) {
cfg := NewBrokerpakSourceConfigFromPath("/path/to/my/pak.brokerpak")
if cfg.ExcludedServices != "" {
t.Fatalf("Expected no excluded services, got: %v", cfg.ExcludedServices)
}
})
}
func ExampleBrokerpakSourceConfig_ExcludedServicesSlice() {
cfg := BrokerpakSourceConfig{ExcludedServices: "FOO\nBAR"}
fmt.Println(cfg.ExcludedServicesSlice())
// Output: [FOO BAR]
}
func ExampleBrokerpakSourceConfig_SetExcludedServices() {
cfg := BrokerpakSourceConfig{}
cfg.SetExcludedServices([]string{"plan1", "plan2"})
fmt.Println("slice:", cfg.ExcludedServicesSlice())
fmt.Println("text:", cfg.ExcludedServices)
// Output: slice: [plan1 plan2]
// text: plan1
// plan2
}
func TestServiceConfig_Validate(t *testing.T) {
cases := map[string]struct {
Cfg ServerConfig
Err string
}{
"missing config": {
Cfg: ServerConfig{
Config: "",
Brokerpaks: nil,
},
Err: "invalid JSON: Config",
},
"bad config": {
Cfg: ServerConfig{
Config: "{}aaa",
Brokerpaks: nil,
},
Err: "invalid JSON: Config",
},
"bad brokerpak keys": {
Cfg: ServerConfig{
Config: "{}",
Brokerpaks: map[string]BrokerpakSourceConfig{
"bad key": NewBrokerpakSourceConfigFromPath("file:///some/path"),
},
},
Err: "field must match '^[a-zA-Z0-9-\\.]+$': Brokerpaks[bad key]",
},
"bad brokerpak values": {
Cfg: ServerConfig{
Config: "{}",
Brokerpaks: map[string]BrokerpakSourceConfig{
"good-key": BrokerpakSourceConfig{
BrokerpakUri: "file:///some/path",
Config: "{}aaa",
},
},
},
Err: "invalid JSON: Brokerpaks[good-key].config",
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
err := tc.Cfg.Validate()
if err == nil {
t.Fatal("expected error, got nil")
}
if err.Error() != tc.Err {
t.Fatalf("Expected %q got %q", tc.Err, err.Error())
}
})
}
}
func ExampleNewServerConfigFromEnv() {
viper.Set("brokerpak.sources", `{"good-key":{"uri":"file://path/to/brokerpak", "config":"{}"}}`)
viper.Set("brokerpak.config", `{}`)
defer viper.Reset() // cleanup
cfg, err := NewServerConfigFromEnv()
if err != nil {
panic(err)
}
fmt.Println("global config:", cfg.Config)
fmt.Println("num services:", len(cfg.Brokerpaks))
// Output: global config: {}
// num services: 1
}
func ExampleNewServerConfigFromEnv_customBuiltin() {
viper.Set("brokerpak.sources", `{}`)
viper.Set("brokerpak.config", `{}`)
viper.Set(brokerpakBuiltinPathKey, "testdata/dummy-brokerpaks")
viper.Set("compatibility.enable-builtin-brokerpaks", "true")
defer viper.Reset() // cleanup
cfg, err := NewServerConfigFromEnv()
if err != nil {
panic(err)
}
fmt.Println("num services:", len(cfg.Brokerpaks))
// Output: num services: 2
}
func TestNewServerConfigFromEnv(t *testing.T) {
cases := map[string]struct {
Config string
Sources string
Err string
}{
"missing config": {
Config: ``,
Sources: `{}`,
Err: `brokerpak config was invalid: invalid JSON: Config`,
},
"bad config": {
Config: `{}aaa`,
Sources: `{}`,
Err: `brokerpak config was invalid: invalid JSON: Config`,
},
"bad brokerpak keys": {
Config: `{}`,
Sources: `{"bad key":{"uri":"file://path/to/brokerpak", "config":"{}"}}`,
Err: `brokerpak config was invalid: field must match '^[a-zA-Z0-9-\.]+$': Brokerpaks[bad key]`,
},
"bad brokerpak values": {
Config: `{}`,
Sources: `{"good-key":{"uri":"file://path/to/brokerpak", "config":"aaa{}"}}`,
Err: `brokerpak config was invalid: invalid JSON: Brokerpaks[good-key].config`,
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
viper.Set("brokerpak.sources", tc.Sources)
viper.Set("brokerpak.config", tc.Config)
defer viper.Reset()
cfg, err := NewServerConfigFromEnv()
if err == nil {
t.Fatal("expected error, got nil")
}
if cfg != nil {
t.Error("Exactly one of cfg and err should be nil")
}
if err.Error() != tc.Err {
t.Fatalf("Expected %q got %q", tc.Err, err.Error())
}
})
}
}
func TestListBrokerpaks(t *testing.T) {
t.Parallel()
cases := map[string]struct {
path string
expectedErr error
expectedPaks []string
}{
"directory does not exist": {
path: "testdata/dne",
expectedErr: nil,
expectedPaks: nil,
},
"directory contains no brokerpaks": {
path: "testdata/no-brokerpaks",
expectedErr: nil,
expectedPaks: nil,
},
"directory contains brokerpaks": {
path: "testdata/dummy-brokerpaks",
expectedErr: nil,
expectedPaks: []string{
"testdata/dummy-brokerpaks/first.brokerpak",
"testdata/dummy-brokerpaks/second.brokerpak",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
paks, err := ListBrokerpaks(tc.path)
if err != nil || tc.expectedErr != nil {
if fmt.Sprint(err) != fmt.Sprint(tc.expectedErr) {
t.Fatalf("expected err: %v got: %v", err, tc.expectedErr)
}
return
}
if !reflect.DeepEqual(tc.expectedPaks, paks) {
t.Fatalf("expected paks: %v got: %v", tc.expectedPaks, paks)
}
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/cmd.go | pkg/brokerpak/cmd.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"fmt"
"io"
"os"
"path/filepath"
"text/tabwriter"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/client"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/generator"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/server"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/stream"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/ziputil"
)
// Init initializes a new brokerpak in the given directory with an example manifest and service definition.
func Init(directory string) error {
exampleManifest := NewExampleManifest()
if err := stream.Copy(stream.FromYaml(exampleManifest), stream.ToFile(directory, manifestName)); err != nil {
return err
}
for _, path := range exampleManifest.ServiceDefinitions {
if err := stream.Copy(stream.FromYaml(tf.NewExampleTfServiceDefinition()), stream.ToFile(directory, path)); err != nil {
return err
}
}
return nil
}
// Pack creates a new brokerpak from the given directory which MUST contain a
// manifest.yml file. If the pack was successful, the returned string will be
// the path to the created brokerpak.
func Pack(directory string) (string, error) {
manifestPath := filepath.Join(directory, manifestName)
manifest := &Manifest{}
if err := stream.Copy(stream.FromFile(manifestPath), stream.ToYaml(manifest)); err != nil {
return "", err
}
packname := fmt.Sprintf("%s-%s.brokerpak", manifest.Name, manifest.Version)
return packname, manifest.Pack(directory, packname)
}
// Info writes out human-readable information about the brokerpak.
func Info(pack string) error {
return finfo(pack, os.Stdout)
}
func finfo(pack string, out io.Writer) error {
brokerPak, err := OpenBrokerPak(pack)
if err != nil {
return err
}
mf, err := brokerPak.Manifest()
if err != nil {
return err
}
services, err := brokerPak.Services()
if err != nil {
return err
}
// Pack information
fmt.Fprintln(out, "Information")
{
w := cmdTabWriter(out)
fmt.Fprintf(w, "format\t%d\n", mf.PackVersion)
fmt.Fprintf(w, "name\t%s\n", mf.Name)
fmt.Fprintf(w, "version\t%s\n", mf.Version)
fmt.Fprintln(w, "platforms")
for _, arch := range mf.Platforms {
fmt.Fprintf(w, "\t%s\n", arch.String())
}
fmt.Fprintln(w, "metadata")
for k, v := range mf.Metadata {
fmt.Fprintf(w, "\t%s\t%s\n", k, v)
}
w.Flush()
fmt.Fprintln(out)
}
{
fmt.Fprintln(out, "Parameters")
w := cmdTabWriter(out)
fmt.Fprintln(w, "NAME\tDESCRIPTION")
for _, param := range mf.Parameters {
fmt.Fprintf(w, "%s\t%s\n", param.Name, param.Description)
}
w.Flush()
fmt.Fprintln(out)
}
{
fmt.Fprintln(out, "Dependencies")
w := cmdTabWriter(out)
fmt.Fprintln(w, "NAME\tVERSION\tSOURCE")
for _, resource := range mf.TerraformResources {
fmt.Fprintf(w, "%s\t%s\t%s\n", resource.Name, resource.Version, resource.Source)
}
w.Flush()
fmt.Fprintln(out)
}
{
fmt.Fprintln(out, "Services")
w := cmdTabWriter(out)
fmt.Fprintln(w, "ID\tNAME\tDESCRIPTION\tPLANS")
for _, svc := range services {
fmt.Fprintf(w, "%s\t%s\t%s\t%d\n", svc.Id, svc.Name, svc.Description, len(svc.Plans))
}
w.Flush()
fmt.Println()
}
fmt.Fprintln(out, "Contents")
ziputil.List(&brokerPak.contents.Reader, out)
fmt.Fprintln(out)
return nil
}
func cmdTabWriter(out io.Writer) *tabwriter.Writer {
// args: output, minwidth, tabwidth, padding, padchar, flags
return tabwriter.NewWriter(out, 0, 0, 2, ' ', tabwriter.StripEscape)
}
// Validate checks the brokerpak for syntactic and limited semantic errors.
func Validate(pack string) error {
brokerPak, err := OpenBrokerPak(pack)
if err != nil {
return err
}
defer brokerPak.Close()
return brokerPak.Validate()
}
// RegisterAll fetches all brokerpaks from the settings file and registers them
// with the given registry.
func RegisterAll(registry broker.BrokerRegistry) error {
pakConfig, err := NewServerConfigFromEnv()
if err != nil {
return err
}
return NewRegistrar(pakConfig).Register(registry)
}
// RunExamples executes the examples from a brokerpak.
func RunExamples(pack string) error {
registry, err := registryFromLocalBrokerpak(pack)
if err != nil {
return err
}
apiClient, err := client.NewClientFromEnv()
if err != nil {
return err
}
allExamples, err := server.GetAllCompleteServiceExamples(registry)
if err != nil {
return err
}
return client.RunExamplesForService(allExamples, apiClient, "", "")
}
// Docs generates the markdown usage docs for the given pack and writes them to stdout.
func Docs(pack string) error {
registry, err := registryFromLocalBrokerpak(pack)
if err != nil {
return err
}
fmt.Println(generator.CatalogDocumentation(registry))
return nil
}
func registryFromLocalBrokerpak(packPath string) (broker.BrokerRegistry, error) {
config := newLocalFileServerConfig(packPath)
registry := broker.BrokerRegistry{}
if err := NewRegistrar(config).Register(registry); err != nil {
return nil, err
}
return registry, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/platform.go | pkg/brokerpak/platform.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"fmt"
"runtime"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
// Platform holds an os/architecture pair.
type Platform struct {
Os string `yaml:"os"`
Arch string `yaml:"arch"`
}
var _ validation.Validatable = (*Platform)(nil)
// Validate implements validation.Validatable.
func (p Platform) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(p.Os, "os"),
validation.ErrIfBlank(p.Arch, "arch"),
)
}
// String formats the platform as an os/arch pair.
func (p Platform) String() string {
return fmt.Sprintf("%s/%s", p.Os, p.Arch)
}
// Equals is an equality test between this platform and the other.
func (p Platform) Equals(other Platform) bool {
return p.String() == other.String()
}
// MatchesCurrent returns true if the platform matches this binary's GOOS/GOARCH combination.
func (p Platform) MatchesCurrent() bool {
return p.Equals(CurrentPlatform())
}
// CurrentPlatform returns the platform defined by GOOS and GOARCH.
func CurrentPlatform() Platform {
return Platform{Os: runtime.GOOS, Arch: runtime.GOARCH}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/registrar.go | pkg/brokerpak/registrar.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf/wrapper"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/spf13/cast"
)
type registrarWalkFunc func(name string, pak BrokerpakSourceConfig, vc *varcontext.VarContext) error
// Registrar is responsible for registering brokerpaks with BrokerRegistries
// subject to the settings provided by a ServerConfig like injecting
// environment variables and skipping certain services.
type Registrar struct {
config *ServerConfig
}
// Register fetches the brokerpaks and registers them with the given registry.
func (r *Registrar) Register(registry broker.BrokerRegistry) error {
registerLogger := utils.NewLogger("brokerpak-registration")
return r.walk(func(name string, pak BrokerpakSourceConfig, vc *varcontext.VarContext) error {
registerLogger.Info("registering", lager.Data{
"name": name,
"location": pak.BrokerpakUri,
"notes": pak.Notes,
"excluded-services": pak.ExcludedServicesSlice(),
"prefix": pak.ServicePrefix,
})
brokerPak, err := DownloadAndOpenBrokerpak(pak.BrokerpakUri)
if err != nil {
return fmt.Errorf("couldn't open brokerpak: %q: %v", pak.BrokerpakUri, err)
}
defer brokerPak.Close()
executor, err := r.createExecutor(brokerPak, vc)
if err != nil {
return err
}
// register the services
services, err := brokerPak.Services()
if err != nil {
return err
}
defns, err := r.toDefinitions(services, pak, executor)
if err != nil {
return err
}
for _, defn := range defns {
registry.Register(defn)
}
return nil
})
}
func (Registrar) toDefinitions(services []tf.TfServiceDefinitionV1, config BrokerpakSourceConfig, executor wrapper.TerraformExecutor) ([]*broker.ServiceDefinition, error) {
var out []*broker.ServiceDefinition
toIgnore := utils.NewStringSet(config.ExcludedServicesSlice()...)
for _, svc := range services {
if toIgnore.Contains(svc.Id) {
continue
}
svc.Name = config.ServicePrefix + svc.Name
bs, err := svc.ToService(executor)
if err != nil {
return nil, err
}
out = append(out, bs)
}
return out, nil
}
func (r *Registrar) createExecutor(brokerPak *BrokerPakReader, vc *varcontext.VarContext) (wrapper.TerraformExecutor, error) {
dir, err := ioutil.TempDir("", "brokerpak")
if err != nil {
return nil, err
}
// extract the Terraform directory
if err := brokerPak.ExtractPlatformBins(dir); err != nil {
return nil, err
}
binPath := filepath.Join(dir, "terraform")
executor := wrapper.CustomTerraformExecutor(binPath, dir, wrapper.DefaultExecutor)
manifest, err := brokerPak.Manifest()
if err != nil {
return nil, err
}
params := r.resolveParameters(manifest.Parameters, vc)
executor = wrapper.CustomEnvironmentExecutor(params, executor)
return executor, nil
}
// resolveParameters resolves environment variables from the given global and
// brokerpak specific.
func (Registrar) resolveParameters(params []ManifestParameter, vc *varcontext.VarContext) map[string]string {
out := make(map[string]string)
context := vc.ToMap()
for _, p := range params {
val, ok := context[p.Name]
if ok {
out[p.Name] = cast.ToString(val)
}
}
return out
}
func (r *Registrar) walk(callback registrarWalkFunc) error {
for name, pak := range r.config.Brokerpaks {
vc, err := varcontext.Builder().
MergeJsonObject(json.RawMessage(r.config.Config)).
MergeJsonObject(json.RawMessage(pak.Config)).
Build()
if err != nil {
return fmt.Errorf("couldn't merge config for brokerpak %q: %v", name, err)
}
if err := callback(name, pak, vc); err != nil {
return err
}
}
return nil
}
// NewRegistrar constructs a new registrar with the given configuration.
// Registrar expects to become the owner of the configuration afterwards.
func NewRegistrar(sc *ServerConfig) *Registrar {
return &Registrar{config: sc}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/pkg/brokerpak/tf_resource_test.go | pkg/brokerpak/tf_resource_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokerpak
import (
"errors"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
func TestTerraformResource_Validate(t *testing.T) {
cases := map[string]validation.ValidatableTest{
"blank obj": {
Object: &TerraformResource{},
Expect: errors.New("missing field(s): name, source, version"),
},
"good obj": {
Object: &TerraformResource{
Name: "foo",
Version: "1.0",
Source: "github.com/myproject",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
tc.Assert(t)
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/root.go | cmd/root.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"fmt"
"log"
"os"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var rootCmd = &cobra.Command{
Use: "gcp-service-broker",
Short: "GCP Service Broker is an OSB compatible service broker",
Long: `An OSB compatible service broker for Google Cloud Platform.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("WARNING: In the future running the broker from the root")
fmt.Println("WARNING: command will show help instead.")
fmt.Println("WARNING: Update your scripts to run gcp-service-broker serve")
serve()
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Configuration file to be read")
viper.SetEnvPrefix(utils.EnvironmentVarPrefix)
viper.SetEnvKeyReplacer(utils.PropertyToEnvReplacer)
viper.AutomaticEnv()
}
func initConfig() {
if cfgFile == "" {
return
}
viper.SetConfigFile(cfgFile)
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Can't read config: %v\n", err)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/client.go | cmd/client.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"encoding/json"
"log"
"github.com/spf13/cobra"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/client"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/server"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
)
var (
serviceId string
planId string
instanceId string
bindingId string
parametersJson string
serviceName string
exampleName string
fileName string
)
func init() {
clientCmd := &cobra.Command{
Use: "client",
Short: "A CLI client for the service broker",
Long: `A CLI client for the service broker.
The client commands use the same configuration values as the server and operate
on localhost using the HTTP protocol.
Configuration Params:
- api.user
- api.password
- api.port
- api.hostname (default: localhost)
Environment Variables:
- GSB_API_USER
- GSB_API_PASSWORD
- GSB_API_PORT
- GSP_API_HOSTNAME
The client commands return formatted JSON when run if the exit code is 0:
{
"url": "http://user:pass@localhost:8000/v2/catalog",
"http_method": "GET",
"status_code": 200,
"response": // Response Body as JSON
}
Exit codes DO NOT correspond with status_code, if a request was made and the
response could be parsed then the exit code will be 0.
Non-zero exit codes indicate a failure in the executable.
Because of the format, you can use the client to do automated testing of your
user-defined plans.
`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
rootCmd.AddCommand(clientCmd)
clientCatalogCmd := newClientCommand("catalog", "Show the service catalog", func(client *client.Client) *client.BrokerResponse {
return client.Catalog()
})
provisionCmd := newClientCommand("provision", "Provision a service", func(client *client.Client) *client.BrokerResponse {
return client.Provision(instanceId, serviceId, planId, json.RawMessage(parametersJson))
})
deprovisionCmd := newClientCommand("deprovision", "Derovision a service", func(client *client.Client) *client.BrokerResponse {
return client.Deprovision(instanceId, serviceId, planId)
})
bindCmd := newClientCommand("bind", "Bind to a service", func(client *client.Client) *client.BrokerResponse {
return client.Bind(instanceId, bindingId, serviceId, planId, json.RawMessage(parametersJson))
})
unbindCmd := newClientCommand("unbind", "Unbind a service", func(client *client.Client) *client.BrokerResponse {
return client.Unbind(instanceId, bindingId, serviceId, planId)
})
lastCmd := newClientCommand("last", "Get the status of the last operation", func(client *client.Client) *client.BrokerResponse {
return client.LastOperation(instanceId)
})
updateCmd := newClientCommand("update", "Update the instance details", func(client *client.Client) *client.BrokerResponse {
return client.Update(instanceId, serviceId, planId, json.RawMessage(parametersJson))
})
runExamplesCmd := &cobra.Command{
Use: "run-examples",
Short: "Run all examples in the use command.",
Long: `Run all examples generated by the use command through a
provision/bind/unbind/deprovision cycle.
Exits with a 0 if all examples were successful, 1 otherwise.`,
Run: func(cmd *cobra.Command, args []string) {
apiClient, err := client.NewClientFromEnv()
if err != nil {
log.Fatalf("Error creating client: %v", err)
}
if exampleName != "" && serviceName == "" {
log.Fatalf("If an example name is specified, you must provide an accompanying service name.")
} else if fileName != "" {
if err := client.RunExamplesFromFile(apiClient, fileName, serviceName, exampleName); err != nil {
log.Fatalf("Error executing examples from file: %v", err)
}
} else if err := client.RunExamplesForService(server.GetExamplesFromServer(), apiClient, serviceName, exampleName); err != nil {
log.Fatalf("Error executing examples: %v", err)
}
log.Println("Success")
},
}
clientCmd.AddCommand(clientCatalogCmd, provisionCmd, deprovisionCmd, bindCmd, unbindCmd, lastCmd, runExamplesCmd, updateCmd)
bindFlag := func(dest *string, name, description string, commands ...*cobra.Command) {
for _, sc := range commands {
sc.Flags().StringVarP(dest, name, "", "", description)
sc.MarkFlagRequired(name)
}
}
bindFlag(&instanceId, "instanceid", "id of the service instance to operate on (user defined)", provisionCmd, deprovisionCmd, bindCmd, unbindCmd, lastCmd, updateCmd)
bindFlag(&serviceId, "serviceid", "GUID of the service instanceid references (see catalog)", provisionCmd, deprovisionCmd, bindCmd, unbindCmd, updateCmd)
bindFlag(&planId, "planid", "GUID of the service instanceid references (see catalog entry for the associated serviceid)", provisionCmd, deprovisionCmd, bindCmd, unbindCmd, updateCmd)
bindFlag(&bindingId, "bindingid", "GUID of the binding to work on (user defined)", bindCmd, unbindCmd)
for _, sc := range []*cobra.Command{provisionCmd, bindCmd, updateCmd} {
sc.Flags().StringVarP(¶metersJson, "params", "", "{}", "JSON string of user-defined parameters to pass to the request")
}
runExamplesCmd.Flags().StringVarP(&serviceName, "service-name", "", "", "name of the service to run tests for")
runExamplesCmd.Flags().StringVarP(&exampleName, "example-name", "", "", "only run examples matching this name")
runExamplesCmd.Flags().StringVarP(&fileName, "filename", "", "", "json file that contains list of CompleteServiceExamples")
}
func newClientCommand(use, short string, run func(*client.Client) *client.BrokerResponse) *cobra.Command {
return &cobra.Command{
Use: use,
Short: short,
Run: func(cmd *cobra.Command, args []string) {
apiClient, err := client.NewClientFromEnv()
if err != nil {
log.Fatalf("Could not create API client: %s", err)
}
results := run(apiClient)
utils.PrettyPrintOrExit(results)
},
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/tf.go | cmd/tf.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"context"
"fmt"
"log"
"os"
"text/tabwriter"
"time"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf/wrapper"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/jinzhu/gorm"
"github.com/spf13/cobra"
)
func init() {
var jobRunner *tf.TfJobRunner
var db *gorm.DB
tfCmd := &cobra.Command{
Use: "tf",
Short: "Interact with the Terraform backend",
Long: `Interact with the Terraform backend`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
logger := utils.NewLogger("tf")
db = db_service.New(logger)
jobRunner, err = tf.NewTfJobRunerFromEnv()
return err
},
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
rootCmd.AddCommand(tfCmd)
tfCmd.AddCommand(&cobra.Command{
Use: "dump",
Short: "dump a Terraform workspace",
Run: func(cmd *cobra.Command, args []string) {
deployment, err := db_service.GetTerraformDeploymentById(context.Background(), args[0])
if err != nil {
log.Fatal(err)
}
ws, err := wrapper.DeserializeWorkspace(deployment.Workspace)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
log.Fatal(err)
}
fmt.Println(ws)
},
})
tfCmd.AddCommand(&cobra.Command{
Use: "wait",
Short: "wait for a Terraform job",
Run: func(cmd *cobra.Command, args []string) {
err := jobRunner.Wait(context.Background(), args[0])
if err != nil {
log.Fatal(err)
}
},
})
tfCmd.AddCommand(&cobra.Command{
Use: "list",
Short: "show the list of Terraform workspaces",
Run: func(cmd *cobra.Command, args []string) {
results := []models.TerraformDeployment{}
if err := db.Find(&results).Error; err != nil {
log.Fatal(err)
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', tabwriter.StripEscape)
fmt.Fprintln(w, "ID\tLast Operation\tState\tLast Updated\tElapsed\tMessage")
for _, result := range results {
lastUpdate := result.UpdatedAt.Format(time.RFC822)
elapsed := ""
if result.LastOperationState == tf.InProgress {
elapsed = time.Now().Sub(result.UpdatedAt).Truncate(time.Second).String()
}
fmt.Fprintf(w, "%q\t%s\t%s\t%s\t%s\t%q\n", result.ID, result.LastOperationType, result.LastOperationState, lastUpdate, elapsed, result.LastOperationMessage)
}
w.Flush()
},
})
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/config.go | cmd/config.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"fmt"
"log"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/config/migration"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/spf13/cobra"
"github.com/spf13/viper"
yaml "gopkg.in/yaml.v2"
)
func init() {
configCmd := &cobra.Command{
Use: "config",
Short: "Show system configuration",
Long: `
The GCP Service Broker can be configured using both environment variables and
configuration files.
It accepts configuration files in YAML, JSON, TOML and Java properties formats.
You can specify a configuration file to read using the --config argument.
You can also specify configurations via environment variables.
The environment variables take the form GSB_<property> where property is the
same name as in the config file transformed to be in upper case and with all
dots replaced with underscores. For example:
GSB_DB_USER_NAME == db.user.name == {"db":{"user":{"name":""}}}
Some older environment variables don't follow this format are aliased so either
format will work.
Precidence is in the order:
environment vars > configuration > defaults
You can show the known coonfiguration values using:
./gcp-service-broker config show
`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
rootCmd.AddCommand(configCmd)
configCmd.AddCommand(&cobra.Command{
Use: "show",
Short: "Show the config",
Long: `Show the current configuration settings.`,
Run: func(cmd *cobra.Command, args []string) {
utils.PrettyPrintOrExit(viper.AllSettings())
},
})
configCmd.AddCommand(&cobra.Command{
Use: "write",
Short: "Write configuration to a file",
Long: `Write configuration to a file in a specified format. Valid extensions are:
* .json
* .yml
* .toml
* .properties
You can combine this command with the --config flag to translate configurations:
GSB_DB_PASSWORD=pass gcp-service-broker --config in.json config write out.toml
out.toml:
[api]
port = "3340"
[db]
name = "servicebroker"
password = "pass"
port = "3306"
`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return viper.WriteConfigAs(args[0])
},
})
configCmd.AddCommand(&cobra.Command{
Use: "migrate-env",
Short: "Run migrations on environment variables and print the changes.",
Long: `Runs migration scripts on the environment variables and prints the changes in a human-readable format.
The original environment variables will not be changed.
This function WILL NOT migrate configuration files.
`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
diff := migration.MigrateEnv()
response, err := yaml.Marshal(diff)
if err != nil {
log.Fatalf("Error marshaling YAML: %s", err)
}
fmt.Println(string(response))
},
})
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/serve.go | cmd/serve.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"context"
"database/sql"
"net/http"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/brokerapi/brokers"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/brokerpak"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/server"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/toggles"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/gorilla/mux"
"github.com/pivotal-cf/brokerapi"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
apiUserProp = "api.user"
apiPasswordProp = "api.password"
apiPortProp = "api.port"
)
var cfCompatibilityToggle = toggles.Features.Toggle("enable-cf-sharing", false, `Set all services to have the Sharable flag so they can be shared
across spaces in Tanzu.`)
func init() {
rootCmd.AddCommand(&cobra.Command{
Use: "serve",
Short: "Start the service broker",
Long: `Starts the service broker listening on a port defined by the
PORT environment variable.`,
Run: func(cmd *cobra.Command, args []string) {
serve()
},
})
rootCmd.AddCommand(&cobra.Command{
Use: "serve-docs",
Short: "Just serve the docs normally available on the broker",
Run: func(cmd *cobra.Command, args []string) {
serveDocs()
},
})
viper.BindEnv(apiUserProp, "SECURITY_USER_NAME")
viper.BindEnv(apiPasswordProp, "SECURITY_USER_PASSWORD")
viper.BindEnv(apiPortProp, "PORT")
}
func serve() {
logger := utils.NewLogger("gcp-service-broker")
db := db_service.New(logger)
// init broker
cfg, err := brokers.NewBrokerConfigFromEnv()
if err != nil {
logger.Fatal("Error initializing service broker config: %s", err)
}
var serviceBroker brokerapi.ServiceBroker
serviceBroker, err = brokers.New(cfg, logger)
if err != nil {
logger.Fatal("Error initializing service broker: %s", err)
}
credentials := brokerapi.BrokerCredentials{
Username: viper.GetString(apiUserProp),
Password: viper.GetString(apiPasswordProp),
}
if cfCompatibilityToggle.IsActive() {
logger.Info("Enabling Cloud Foundry service sharing")
serviceBroker = server.NewCfSharingWrapper(serviceBroker)
}
services, err := serviceBroker.Services(context.Background())
if err != nil {
logger.Error("creating service catalog", err)
}
logger.Info("service catalog", lager.Data{"catalog": services})
brokerAPI := brokerapi.New(serviceBroker, logger, credentials)
startServer(cfg.Registry, db.DB(), brokerAPI)
}
func serveDocs() {
logger := utils.NewLogger("gcp-service-broker")
// init broker
registry := builtin.BuiltinBrokerRegistry()
if err := brokerpak.RegisterAll(registry); err != nil {
logger.Error("loading brokerpaks", err)
}
startServer(registry, nil, nil)
}
func startServer(registry broker.BrokerRegistry, db *sql.DB, brokerapi http.Handler) {
logger := utils.NewLogger("gcp-service-broker")
router := mux.NewRouter()
// match paths going to the brokerapi first
if brokerapi != nil {
router.PathPrefix("/v2").Handler(brokerapi)
}
server.AddDocsHandler(router, registry)
router.HandleFunc("/examples", server.NewExampleHandler(registry))
server.AddHealthHandler(router, db)
port := viper.GetString(apiPortProp)
logger.Info("Serving", lager.Data{"port": port})
http.ListenAndServe(":"+port, router)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/version.go | cmd/version.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"fmt"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/spf13/cobra"
)
func init() {
versionCmd := &cobra.Command{
Use: "version",
Short: "Show the version info of the broker",
Long: `Show the version info of the broker`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(utils.Version)
},
}
rootCmd.AddCommand(versionCmd)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/generate.go | cmd/generate.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"fmt"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/generator"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin"
"github.com/spf13/cobra"
)
func init() {
generateCmd := &cobra.Command{
Use: "generate",
Short: "Generate documentation and tiles",
Long: `Generate documentation and tiles`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
rootCmd.AddCommand(generateCmd)
var useDestinationDir string
useCmd := &cobra.Command{
Use: "use",
Short: "Generate use markdown file",
Long: `Generates the use.md file with:
* details about what each service is
* available parameters
`,
Run: func(cmd *cobra.Command, args []string) {
if useDestinationDir == "" {
fmt.Println(generator.CatalogDocumentation(builtin.BuiltinBrokerRegistry()))
} else {
generator.CatalogDocumentationToDir(builtin.BuiltinBrokerRegistry(), useDestinationDir)
}
},
}
useCmd.Flags().StringVar(&useDestinationDir, "destination-dir", "", "Destination directory to generate usage docs about all available broker classes")
generateCmd.AddCommand(useCmd)
generateCmd.AddCommand(&cobra.Command{
Use: "customization",
Short: "Generate customization documentation",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(generator.GenerateCustomizationMd())
},
})
generateCmd.AddCommand(&cobra.Command{
Use: "tile",
Short: "Generate tile.yml file",
Run: func(cmd *cobra.Command, args []string) {
fmt.Print(generator.GenerateTile())
},
})
generateCmd.AddCommand(&cobra.Command{
Use: "manifest",
Short: "Generate manifest.yml file",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(generator.GenerateManifest())
},
})
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/cmd/pak.go | cmd/pak.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 cmd
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/brokerpak"
"github.com/spf13/cobra"
)
func init() {
pakCmd := &cobra.Command{
Use: "pak",
Short: "interact with user-defined service definition bundles",
Long: `Lets you create, validate, and view service definition bundles.
A service definition bundle is a zip file containing all the elements needed
to define and run a custom service.
Bundles include source code (for legal compliance), service definitions, and
Terraform/provider binaries for multiple platforms. They give you a contained
way to deploy new services to existing brokers or augment the broker to fit
your needs.
To start building a pack, create a new directory and within it run init:
gcp-service-broker pak init my-pak
You'll get a new pack with a manifest and example service definition.
Define the architectures and Terraform plugins you need in your manifest along
with any metadata you want, and include the names of all service definition
files.
When you're done, you can build the bundle which will download the sources,
Terraform resources, and pack them together.
gcp-service-broker pak build my-pak
This will produce a pack:
my-pak.brokerpak
You can run validation on an existing pack you created or downloaded:
gcp-service-broker pak validate my-pak.brokerpak
You can also list information about the pack which includes metadata,
dependencies, services it provides, and the contents.
gcp-service-broker pak info my-pak.brokerpak
`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
rootCmd.AddCommand(pakCmd)
pakCmd.AddCommand(&cobra.Command{
Use: "init [path/to/pack/directory]",
Short: "initialize a brokerpak manifest and example service",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
directory := ""
if len(args) == 1 {
directory = args[0]
}
if err := brokerpak.Init(directory); err != nil {
log.Fatalf("error while packing %q: %v", directory, err)
}
},
})
pakCmd.AddCommand(&cobra.Command{
Use: "build [path/to/pack/directory]",
Short: "bundle up the service definition files and Terraform resources into a brokerpak",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
directory := ""
if len(args) == 1 {
directory = args[0]
}
pakPath, err := brokerpak.Pack(directory)
if err != nil {
log.Fatalf("error while packing %q: %v", directory, err)
}
if err := brokerpak.Validate(pakPath); err != nil {
log.Fatalf("created: %v, but it failed validity checking: %v\n", pakPath, err)
} else {
fmt.Printf("created: %v\n", pakPath)
}
},
})
pakCmd.AddCommand(&cobra.Command{
Use: "info [pack.brokerpak]",
Short: "get info about a brokerpak",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if err := brokerpak.Info(args[0]); err != nil {
log.Fatalf("error getting info for %q: %v", args[0], err)
}
},
})
pakCmd.AddCommand(&cobra.Command{
Use: "validate [pack.brokerpak]",
Short: "validate a brokerpak",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if err := brokerpak.Validate(args[0]); err != nil {
log.Fatalf("Error: %v\n", err)
} else {
log.Println("Valid")
}
},
})
pakCmd.AddCommand(&cobra.Command{
Use: "run-examples [pack.brokerpak]",
Short: "run the examples from a brokerpak",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if err := brokerpak.RunExamples(args[0]); err != nil {
log.Fatalf("Error executing examples: %v", err)
}
log.Println("Success")
},
})
pakCmd.AddCommand(&cobra.Command{
Use: "docs [pack.brokerpak]",
Aliases: []string{"use"},
Short: "generate the markdown usage docs for the given pack",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
brokerpak.Docs(args[0])
},
})
pakCmd.AddCommand(&cobra.Command{
Use: "test",
Short: "Run an integration test for the workflow",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
// Runs a quick and dirty e2e test for the development pattern
td, err := ioutil.TempDir("", "test-brokerpak")
if err != nil {
log.Fatalf("couldn't initialize temp directory: %v", err)
}
defer os.RemoveAll(td)
if err := brokerpak.Init(td); err != nil {
log.Fatalf("couldn't initialize brokerpak: %v", err)
}
// Edit the manifest to point to our local server
packname, err := brokerpak.Pack(td)
defer os.Remove(packname)
if err != nil {
log.Fatalf("couldn't pack brokerpak: %v", err)
}
if err := brokerpak.Validate(packname); err != nil {
log.Fatalf("couldn't validate brokerpak: %v", err)
}
log.Println("success!")
},
})
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/tools/osdfgen/osdfgen_test.go | tools/osdfgen/osdfgen_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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.
// +build !service_broker
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"gopkg.in/src-d/go-license-detector.v2/licensedb/filer"
)
const ExampleLicense = `Copyright 2018 the Service Broker Project Authors.
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.`
func TestShouldIncludeFileInOsdf(t *testing.T) {
cases := map[string]struct {
FileName string
SpdxCode string
Expected bool
}{
"apache2 notice": {"NOTICE", "Apache-2.0", true},
"MIT notice": {"NOTICE", "MIT", false},
"upper license": {"LICENSE", "MIT", true},
"lower license": {"license", "MIT", true},
"mixed license": {"License", "MIT", true},
"extension license": {"License.txt", "MIT", true},
"non-license": {"main.go", "MIT", false},
"license directory": {"license/", "MIT", false},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
fd := filer.File{IsDir: strings.HasSuffix(tc.FileName, "/"), Name: tc.FileName}
if shouldIncludeFileInOsdf(fd, tc.SpdxCode) != tc.Expected {
t.Error("Expected", tc.Expected, " Got", !tc.Expected)
}
})
}
}
func TestMostLikelyLicense(t *testing.T) {
cases := map[string]struct {
LicenseList map[string]float32
Expected string
}{
"single": {map[string]float32{"mit": 0}, "mit"},
"multiple": {map[string]float32{"mit": 1, "bsd": 0}, "mit"},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual, _ := mostLikelyLicense(tc.LicenseList)
if tc.Expected != actual {
t.Error("Expected", tc.Expected, " Got", actual)
}
})
}
}
func ExampleDetectLicenses() {
dir, err := ioutil.TempDir("", "lic")
if err != nil {
panic(err)
}
if err := ioutil.WriteFile(filepath.Join(dir, "LICENSE"), []byte(ExampleLicense), 0666); err != nil {
panic(err)
}
lic, err := detectLicenses(dir)
if err != nil {
panic(err)
}
fmt.Println(lic)
// Output: map[Apache-2.0:1]
}
func ExampleGetLicenseText() {
dir, err := ioutil.TempDir("", "lic")
if err != nil {
panic(err)
}
proj := &Dependency{
ParentDirectory: dir,
Project: Project{
Name: "foo",
Revision: "xxx-my-revision-here-xxx",
},
}
if err := os.MkdirAll(proj.Directory(), 0777); err != nil {
panic(err)
}
if err := ioutil.WriteFile(filepath.Join(proj.Directory(), "LICENSE"), []byte(ExampleLicense), 0666); err != nil {
panic(err)
}
lic, err := getLicenseText(proj, "Apache-2.0")
if err != nil {
panic(err)
}
fmt.Println(lic)
// Output: Contents of: foo/LICENSE@xxx-my-revision-here-xxx
//
// Copyright 2018 the Service Broker Project Authors.
//
// 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.
}
func ExampleGetProjects() {
dir, err := ioutil.TempDir("", "")
if err != nil {
panic(err)
}
lockFile := `
[[projects]]
digest = "1:82f6c9a55c0bd9744064418f049d5232bb8b8cc45eb32e72c0adefaf158a0f9b"
name = "github.com/hashicorp/go-safetemp"
packages = ["."]
pruneopts = ""
revision = "c9a55de4fe06c920a71964b53cfe3dd293a3c743"
version = "v1.0.0"
[[projects]]
digest = "1:8c7fb7f81c06add10a17362abc1ae569ff9765a26c061c6b6e67c909f4f414db"
name = "github.com/hashicorp/go-version"
packages = ["."]
pruneopts = ""
revision = "b5a281d3160aa11950a6182bd9a9dc2cb1e02d50"
version = "v1.0.0"
`
if err := ioutil.WriteFile(filepath.Join(dir, "Gopkg.lock"), []byte(lockFile), 0666); err != nil {
panic(err)
}
for _, p := range getProjects(dir) {
fmt.Println(p.Name)
}
// Output: github.com/hashicorp/go-safetemp
// github.com/hashicorp/go-version
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/tools/osdfgen/osdfgen.go | tools/osdfgen/osdfgen.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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.
// +build !service_broker
// `osdfgen` can be used to build a CSV suitable for uploading to Pivotal's
// [OSDF Generator](http://osdf-generator.cfapps.io/static/index.html).
// It determines licenses by sniffing the dependencies listed in `Gopkg.lock`.
// Example: go run osdfgen.go -p ../../ -o test.csv
// The `-p` flag points at the project root and the `-o` flag is the place to put the output (stdout by default).
package main
import (
"bytes"
"encoding/csv"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"math"
"os"
"path/filepath"
"strings"
"text/template"
"gopkg.in/src-d/go-license-detector.v2/licensedb"
"gopkg.in/src-d/go-license-detector.v2/licensedb/filer"
toml "github.com/pelletier/go-toml"
)
type Lockfile struct {
Projects []Project
}
type Project struct {
Name string
Revision string
}
type Dependency struct {
ParentDirectory string
Project Project
}
func (d *Dependency) Directory() string {
return filepath.Join(d.ParentDirectory, "vendor", d.Project.Name)
}
func main() {
out := flag.String("o", "-", "Sets the output location of the OSDF csv")
proj := flag.String("p", ".", "The project root")
templateStr := flag.String("t", "{{(csv .dependency.Project.Name .dependency.Project.Revision .spdxCode .licenseText)}}", "Template to use")
detectOverrideJSON := flag.String("d", "{}", "A JSON object of dep path -> SPDX overrides")
flag.Parse()
outputTemplate, err := parseTemplate(*templateStr)
if err != nil {
log.Fatal("couldn't parse template: ", err)
}
var detectOverrides map[string]string
if err := json.Unmarshal([]byte(*detectOverrideJSON), &detectOverrides); err != nil {
log.Fatal("couldn't parse detect overrides: ", err)
}
buf := &bytes.Buffer{}
for _, project := range getProjects(*proj) {
dep := &Dependency{
ParentDirectory: *proj,
Project: project,
}
var licenses map[string]float32
var err error
if overrideSPDX, ok := detectOverrides[project.Name]; ok {
licenses = map[string]float32{
overrideSPDX: 1.0,
}
} else {
licenses, err = detectLicenses(dep.Directory())
if err != nil {
log.Fatalf("couldn't detect licenses for %q in %q: %s", project.Name, dep.Directory(), err)
}
}
spdxCode, probability := mostLikelyLicense(licenses)
licenseText, err := getLicenseText(dep, spdxCode)
if err != nil {
log.Fatalf("couldn't get license text for %q: %s", project.Name, err)
}
err = outputTemplate.Execute(buf, map[string]interface{}{
"dependency": dep,
"spdxCode": spdxCode,
"spdxProbability": probability,
"licenseText": licenseText,
})
if err != nil {
log.Fatal(err)
}
}
writeOutput(*out, buf)
}
// detectLicenses returns a map of the SPDX codes for the licenses in a given
// directory.
func detectLicenses(directory string) (map[string]float32, error) {
dir, err := filer.FromDirectory(directory)
if err != nil {
return nil, fmt.Errorf("couldn't find dep %q in vendor %s", dir, err)
}
return licensedb.Detect(dir)
}
// writeOutput writes the contents of src into the file denoted by fileName.
// if fileName is "-" the UNIX convention is followed and the contents are
// written to stdout.
func writeOutput(fileName string, src io.Reader) {
var dest io.Writer
if fileName == "-" {
dest = os.Stdout
} else {
var err error
fd, err := os.Create(fileName)
if err != nil {
log.Fatalf("Error opening %q, %s", fileName, err)
}
defer fd.Close()
dest = fd
}
if _, err := io.Copy(dest, src); err != nil {
log.Fatalf("Error trying to write output: %v", err)
}
}
// getProjects reads a Gopkg.lock file and returns a list of the projects it
// contains.
func getProjects(projectRoot string) []Project {
tree, err := toml.LoadFile(filepath.Join(projectRoot, "Gopkg.lock"))
if err != nil {
log.Fatalf("Error loading Gopkg.lock, %s", err)
}
deps := Lockfile{}
if err := tree.Unmarshal(&deps); err != nil {
log.Fatalf("Error unmarshaling lockfile %s", err)
}
return deps.Projects
}
// mostLikelyLicense finds the key in a map with the greatest value.
func mostLikelyLicense(m map[string]float32) (spdxCode string, probability float32) {
var maxVal float32 = -math.MaxFloat32
maxKey := ""
for k, v := range m {
if v > maxVal {
maxVal = v
maxKey = k
}
}
return maxKey, maxVal
}
// getLicenseText creates a copy of the licence text(s) and notice(s) for a
// given project.
// Returns an error if no license could be found.
func getLicenseText(project *Dependency, spdxCode string) (string, error) {
dir, err := filer.FromDirectory(project.Directory())
if err != nil {
log.Fatalf("Could not find dep %q in vendor %s", project.Project.Name, err)
}
entries, err := dir.ReadDir(".")
if err != nil {
log.Fatalf("Could not find dep %q in vendor %s", project.Project.Name, err)
}
licenses := ""
for _, entry := range entries {
if !shouldIncludeFileInOsdf(entry, spdxCode) {
continue
}
licenses += fmt.Sprintf("Contents of: %s/%s@%s\n\n", project.Project.Name, entry.Name, project.Project.Revision)
text, err := dir.ReadFile(entry.Name)
if err != nil {
return licenses, err
}
licenses += string(text)
licenses += "\n\n"
}
if licenses == "" {
return "", errors.New("Could not find license text")
}
return licenses, nil
}
// A file should be included in the OSDF if it's a license, or the license is
// Apache and it's a notice.
func shouldIncludeFileInOsdf(file filer.File, spdxCode string) bool {
if file.IsDir {
return false
}
lowerName := strings.ToLower(file.Name)
isLicense := strings.Contains(lowerName, "license")
// We're required to include NOTICE files for Apache 2 licensed products.
isNotice := lowerName == "notice" && spdxCode == "Apache-2.0"
return isLicense || isNotice
}
func parseTemplate(templateString string) (*template.Template, error) {
return template.New("tmpl").Funcs(template.FuncMap{
"csv": csvFormatter,
}).Parse(templateString)
}
func csvFormatter(input ...interface{}) string {
var columns []string
for _, v := range input {
columns = append(columns, fmt.Sprintf("%v", v))
}
buf := &bytes.Buffer{}
writer := csv.NewWriter(buf)
writer.Write(columns)
writer.Flush()
return buf.String()
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/brokerapi/brokers/broker_config_test.go | brokerapi/brokers/broker_config_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 brokers
import (
"os"
"reflect"
"testing"
"golang.org/x/oauth2/jwt"
)
const testServiceAccountJson = `{
"type": "service_account",
"project_id": "foo",
"private_key_id": "something",
"private_key": "foobar",
"client_email": "example@gmail.com",
"client_id": "1",
"auth_uri": "somelink",
"token_uri": "somelink",
"auth_provider_x509_cert_url": "somelink",
"client_x509_cert_url": "somelink"
}`
func TestNewBrokerConfigFromEnv(t *testing.T) {
os.Setenv("ROOT_SERVICE_ACCOUNT_JSON", testServiceAccountJson)
defer os.Unsetenv("ROOT_SERVICE_ACCOUNT_JSON")
cfg, err := NewBrokerConfigFromEnv()
if err != nil {
t.Fatal(err)
}
t.Run("has-default-client", func(t *testing.T) {
if cfg.HttpConfig == nil {
t.Fatal("Expected HttpCofnig to be non-nil, got: <nil>")
}
if reflect.DeepEqual(cfg.HttpConfig, &jwt.Config{}) {
t.Errorf("Expected HttpConfig to not be an empty JWT config, got: %#v", cfg.HttpConfig)
}
})
t.Run("parsed-projectid-from-config", func(t *testing.T) {
if !reflect.DeepEqual(cfg.ProjectId, "foo") {
t.Errorf("Expected ProjectId to be %v, got: %v", "foo", cfg.ProjectId)
}
})
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/brokerapi/brokers/gcp_service_broker.go | brokerapi/brokers/gcp_service_broker.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokers
import (
"context"
"errors"
"fmt"
"net/http"
"code.cloudfoundry.org/lager"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
"google.golang.org/api/googleapi"
"encoding/json"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
)
var (
invalidUserInputMsg = "User supplied paramaters must be in the form of a valid JSON map."
ErrInvalidUserInput = brokerapi.NewFailureResponse(errors.New(invalidUserInputMsg), http.StatusBadRequest, "parsing-user-request")
ErrGetInstancesUnsupported = brokerapi.NewFailureResponse(errors.New("the service_instances endpoint is unsupported"), http.StatusBadRequest, "unsupported")
ErrGetBindingsUnsupported = brokerapi.NewFailureResponse(errors.New("the service_bindings endpoint is unsupported"), http.StatusBadRequest, "unsupported")
)
// GCPServiceBroker is a brokerapi.ServiceBroker that can be used to generate an OSB compatible service broker.
type GCPServiceBroker struct {
registry broker.BrokerRegistry
jwtConfig *jwt.Config
projectId string
Logger lager.Logger
}
// New creates a GCPServiceBroker.
// Exactly one of GCPServiceBroker or error will be nil when returned.
func New(cfg *BrokerConfig, logger lager.Logger) (*GCPServiceBroker, error) {
return &GCPServiceBroker{
registry: cfg.Registry,
jwtConfig: cfg.HttpConfig,
projectId: cfg.ProjectId,
Logger: logger,
}, nil
}
// Services lists services in the broker's catalog.
// It is called through the `GET /v2/catalog` endpoint or the `cf marketplace` command.
func (gcpBroker *GCPServiceBroker) Services(ctx context.Context) ([]brokerapi.Service, error) {
svcs := []brokerapi.Service{}
enabledServices, err := gcpBroker.registry.GetEnabledServices()
if err != nil {
return nil, err
}
for _, service := range enabledServices {
entry, err := service.CatalogEntry()
if err != nil {
return svcs, err
}
svcs = append(svcs, entry.ToPlain())
}
return svcs, nil
}
func (gcpBroker *GCPServiceBroker) getDefinitionAndProvider(serviceId string) (*broker.ServiceDefinition, broker.ServiceProvider, error) {
defn, err := gcpBroker.registry.GetServiceById(serviceId)
if err != nil {
return nil, nil, err
}
providerBuilder := defn.ProviderBuilder(gcpBroker.projectId, gcpBroker.jwtConfig, gcpBroker.Logger)
return defn, providerBuilder, nil
}
// Provision creates a new instance of a service.
// It is bound to the `PUT /v2/service_instances/:instance_id` endpoint and can be called using the `cf create-service` command.
func (gcpBroker *GCPServiceBroker) Provision(ctx context.Context, instanceID string, details brokerapi.ProvisionDetails, clientSupportsAsync bool) (brokerapi.ProvisionedServiceSpec, error) {
gcpBroker.Logger.Info("Provisioning", lager.Data{
"instanceId": instanceID,
"accepts_incomplete": clientSupportsAsync,
"details": details,
})
// make sure that instance hasn't already been provisioned
exists, err := db_service.ExistsServiceInstanceDetailsById(ctx, instanceID)
if err != nil {
return brokerapi.ProvisionedServiceSpec{}, fmt.Errorf("Database error checking for existing instance: %s", err)
}
if exists {
return brokerapi.ProvisionedServiceSpec{}, brokerapi.ErrInstanceAlreadyExists
}
brokerService, serviceHelper, err := gcpBroker.getDefinitionAndProvider(details.ServiceID)
if err != nil {
return brokerapi.ProvisionedServiceSpec{}, err
}
// verify the service exists and the plan exists
plan, err := brokerService.GetPlanById(details.PlanID)
if err != nil {
return brokerapi.ProvisionedServiceSpec{}, err
}
// verify async provisioning is allowed if it is required
shouldProvisionAsync := serviceHelper.ProvisionsAsync()
if shouldProvisionAsync && !clientSupportsAsync {
return brokerapi.ProvisionedServiceSpec{}, brokerapi.ErrAsyncRequired
}
// Give the user a better error message if they give us a bad request
if !isValidOrEmptyJSON(details.GetRawParameters()) {
return brokerapi.ProvisionedServiceSpec{}, ErrInvalidUserInput
}
// validate parameters meet the service's schema and merge the user vars with
// the plan's
vars, err := brokerService.ProvisionVariables(instanceID, details, *plan)
if err != nil {
return brokerapi.ProvisionedServiceSpec{}, err
}
// get instance details
instanceDetails, err := serviceHelper.Provision(ctx, vars)
if err != nil {
return brokerapi.ProvisionedServiceSpec{}, err
}
// save instance details
instanceDetails.ServiceId = details.ServiceID
instanceDetails.ID = instanceID
instanceDetails.PlanId = details.PlanID
instanceDetails.SpaceGuid = details.SpaceGUID
instanceDetails.OrganizationGuid = details.OrganizationGUID
err = db_service.CreateServiceInstanceDetails(ctx, &instanceDetails)
if err != nil {
return brokerapi.ProvisionedServiceSpec{}, fmt.Errorf("Error saving instance details to database: %s. WARNING: this instance cannot be deprovisioned through cf. Contact your operator for cleanup", err)
}
// save provision request details
pr := models.ProvisionRequestDetails{
ServiceInstanceId: instanceID,
RequestDetails: string(details.RawParameters),
}
if err = db_service.CreateProvisionRequestDetails(ctx, &pr); err != nil {
return brokerapi.ProvisionedServiceSpec{}, fmt.Errorf("Error saving provision request details to database: %s. Services relying on async provisioning will not be able to complete provisioning", err)
}
return brokerapi.ProvisionedServiceSpec{IsAsync: shouldProvisionAsync, DashboardURL: "", OperationData: instanceDetails.OperationId}, nil
}
// Deprovision destroys an existing instance of a service.
// It is bound to the `DELETE /v2/service_instances/:instance_id` endpoint and can be called using the `cf delete-service` command.
// If a deprovision is asynchronous, the returned DeprovisionServiceSpec will contain the operation ID for tracking its progress.
func (gcpBroker *GCPServiceBroker) Deprovision(ctx context.Context, instanceID string, details brokerapi.DeprovisionDetails, clientSupportsAsync bool) (response brokerapi.DeprovisionServiceSpec, err error) {
gcpBroker.Logger.Info("Deprovisioning", lager.Data{
"instance_id": instanceID,
"accepts_incomplete": clientSupportsAsync,
"details": details,
})
// make sure that instance actually exists
instance, err := db_service.GetServiceInstanceDetailsById(ctx, instanceID)
if err != nil {
return response, brokerapi.ErrInstanceDoesNotExist
}
_, serviceProvider, err := gcpBroker.getDefinitionAndProvider(instance.ServiceId)
if err != nil {
return response, err
}
// if async deprovisioning isn't allowed but this service needs it, throw an error
if serviceProvider.DeprovisionsAsync() && !clientSupportsAsync {
return response, brokerapi.ErrAsyncRequired
}
operationId, err := serviceProvider.Deprovision(ctx, *instance, details)
if err != nil {
return response, err
}
if operationId == nil {
// soft-delete instance details from the db if this is a synchronous operation
// if it's an async operation we can't delete from the db until we're sure delete succeeded, so this is
// handled internally to LastOperation
if err := db_service.DeleteServiceInstanceDetailsById(ctx, instanceID); err != nil {
return response, fmt.Errorf("Error deleting instance details from database: %s. WARNING: this instance will remain visible in cf. Contact your operator for cleanup", err)
}
return response, nil
} else {
response.IsAsync = true
response.OperationData = *operationId
instance.OperationType = models.DeprovisionOperationType
instance.OperationId = *operationId
if err := db_service.SaveServiceInstanceDetails(ctx, instance); err != nil {
return response, fmt.Errorf("Error saving instance details to database: %s. WARNING: this instance will remain visible in cf. Contact your operator for cleanup.", err)
}
return response, nil
}
}
// Bind creates an account with credentials to access an instance of a service.
// It is bound to the `PUT /v2/service_instances/:instance_id/service_bindings/:binding_id` endpoint and can be called using the `cf bind-service` command.
func (gcpBroker *GCPServiceBroker) Bind(ctx context.Context, instanceID, bindingID string, details brokerapi.BindDetails, clientSupportsAsync bool) (brokerapi.Binding, error) {
gcpBroker.Logger.Info("Binding", lager.Data{
"instance_id": instanceID,
"binding_id": bindingID,
"details": details,
})
// check for existing binding
exists, err := db_service.ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx, instanceID, bindingID)
if err != nil {
return brokerapi.Binding{}, fmt.Errorf("Error checking for existing binding: %s", err)
}
if exists {
return brokerapi.Binding{}, brokerapi.ErrBindingAlreadyExists
}
// get existing service instance details
instanceRecord, err := db_service.GetServiceInstanceDetailsById(ctx, instanceID)
if err != nil {
return brokerapi.Binding{}, fmt.Errorf("Error retrieving service instance details: %s", err)
}
serviceDefinition, serviceProvider, err := gcpBroker.getDefinitionAndProvider(instanceRecord.ServiceId)
if err != nil {
return brokerapi.Binding{}, err
}
// verify the service exists and the plan exists
plan, err := serviceDefinition.GetPlanById(details.PlanID)
if err != nil {
return brokerapi.Binding{}, err
}
// Give the user a better error message if they give us a bad request
if !isValidOrEmptyJSON(details.GetRawParameters()) {
return brokerapi.Binding{}, ErrInvalidUserInput
}
// validate parameters meet the service's schema and merge the plan's vars with
// the user's
vars, err := serviceDefinition.BindVariables(*instanceRecord, bindingID, details, plan)
if err != nil {
return brokerapi.Binding{}, err
}
// create binding
credsDetails, err := serviceProvider.Bind(ctx, vars)
if err != nil {
return brokerapi.Binding{}, err
}
serializedCreds, err := json.Marshal(credsDetails)
if err != nil {
return brokerapi.Binding{}, fmt.Errorf("Error serializing credentials: %s. WARNING: these credentials cannot be unbound through cf. Please contact your operator for cleanup", err)
}
// save binding to database
newCreds := models.ServiceBindingCredentials{
ServiceInstanceId: instanceID,
BindingId: bindingID,
ServiceId: details.ServiceID,
OtherDetails: string(serializedCreds),
}
if err := db_service.CreateServiceBindingCredentials(ctx, &newCreds); err != nil {
return brokerapi.Binding{}, fmt.Errorf("Error saving credentials to database: %s. WARNING: these credentials cannot be unbound through cf. Please contact your operator for cleanup",
err)
}
binding, err := serviceProvider.BuildInstanceCredentials(ctx, newCreds, *instanceRecord)
if err != nil {
return brokerapi.Binding{}, err
}
return *binding, nil
}
// GetBinding fetches an existing service binding.
// GET /v2/service_instances/{instance_id}/service_bindings/{binding_id}
//
// NOTE: This functionality is not implemented.
func (broker *GCPServiceBroker) GetBinding(ctx context.Context, instanceID, bindingID string) (brokerapi.GetBindingSpec, error) {
broker.Logger.Info("GetBinding", lager.Data{
"instance_id": instanceID,
"binding_id": bindingID,
})
return brokerapi.GetBindingSpec{}, ErrGetBindingsUnsupported
}
// GetInstance fetches information about a service instance
// GET /v2/service_instances/{instance_id}
//
// NOTE: This functionality is not implemented.
func (broker *GCPServiceBroker) GetInstance(ctx context.Context, instanceID string) (brokerapi.GetInstanceDetailsSpec, error) {
broker.Logger.Info("GetInstance", lager.Data{
"instance_id": instanceID,
})
return brokerapi.GetInstanceDetailsSpec{}, ErrGetInstancesUnsupported
}
// LastBindingOperation fetches last operation state for a service binding.
// GET /v2/service_instances/{instance_id}/service_bindings/{binding_id}/last_operation
//
// NOTE: This functionality is not implemented.
func (broker *GCPServiceBroker) LastBindingOperation(ctx context.Context, instanceID, bindingID string, details brokerapi.PollDetails) (brokerapi.LastOperation, error) {
broker.Logger.Info("LastBindingOperation", lager.Data{
"instance_id": instanceID,
"binding_id": bindingID,
"plan_id": details.PlanID,
"service_id": details.ServiceID,
"operation_data": details.OperationData,
})
return brokerapi.LastOperation{}, brokerapi.ErrAsyncRequired
}
// Unbind destroys an account and credentials with access to an instance of a service.
// It is bound to the `DELETE /v2/service_instances/:instance_id/service_bindings/:binding_id` endpoint and can be called using the `cf unbind-service` command.
func (gcpBroker *GCPServiceBroker) Unbind(ctx context.Context, instanceID, bindingID string, details brokerapi.UnbindDetails, asyncSupported bool) (brokerapi.UnbindSpec, error) {
gcpBroker.Logger.Info("Unbinding", lager.Data{
"instance_id": instanceID,
"binding_id": bindingID,
"details": details,
})
_, serviceProvider, err := gcpBroker.getDefinitionAndProvider(details.ServiceID)
if err != nil {
return brokerapi.UnbindSpec{}, err
}
// validate existence of binding
existingBinding, err := db_service.GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx, instanceID, bindingID)
if err != nil {
return brokerapi.UnbindSpec{}, brokerapi.ErrBindingDoesNotExist
}
// get existing service instance details
instance, err := db_service.GetServiceInstanceDetailsById(ctx, instanceID)
if err != nil {
return brokerapi.UnbindSpec{}, fmt.Errorf("Error retrieving service instance details: %s", err)
}
// remove binding from Google
if err := serviceProvider.Unbind(ctx, *instance, *existingBinding); err != nil {
return brokerapi.UnbindSpec{}, err
}
// remove binding from database
if err := db_service.DeleteServiceBindingCredentials(ctx, existingBinding); err != nil {
return brokerapi.UnbindSpec{}, fmt.Errorf("Error soft-deleting credentials from database: %s. WARNING: these credentials will remain visible in cf. Contact your operator for cleanup", err)
}
return brokerapi.UnbindSpec{}, nil
}
// LastOperation fetches last operation state for a service instance.
// It is bound to the `GET /v2/service_instances/:instance_id/last_operation` endpoint.
// It is called by `cf create-service` or `cf delete-service` if the operation was asynchronous.
func (gcpBroker *GCPServiceBroker) LastOperation(ctx context.Context, instanceID string, details brokerapi.PollDetails) (brokerapi.LastOperation, error) {
gcpBroker.Logger.Info("Last Operation", lager.Data{
"instance_id": instanceID,
"plan_id": details.PlanID,
"service_id": details.ServiceID,
"operation_data": details.OperationData,
})
instance, err := db_service.GetServiceInstanceDetailsById(ctx, instanceID)
if err != nil {
return brokerapi.LastOperation{}, brokerapi.ErrInstanceDoesNotExist
}
_, serviceProvider, err := gcpBroker.getDefinitionAndProvider(instance.ServiceId)
if err != nil {
return brokerapi.LastOperation{}, err
}
isAsyncService := serviceProvider.ProvisionsAsync() || serviceProvider.DeprovisionsAsync()
if !isAsyncService {
return brokerapi.LastOperation{}, brokerapi.ErrAsyncRequired
}
lastOperationType := instance.OperationType
done, err := serviceProvider.PollInstance(ctx, *instance)
if err != nil {
// this is a retryable error
if gerr, ok := err.(*googleapi.Error); ok {
if gerr.Code == 503 {
return brokerapi.LastOperation{State: brokerapi.InProgress}, err
}
}
// This is not a retryable error. Return fail
return brokerapi.LastOperation{State: brokerapi.Failed}, err
}
if !done {
return brokerapi.LastOperation{State: brokerapi.InProgress}, nil
}
// the instance may have been invalidated, so we pass its primary key rather than the
// instance directly.
updateErr := gcpBroker.updateStateOnOperationCompletion(ctx, serviceProvider, lastOperationType, instanceID)
return brokerapi.LastOperation{State: brokerapi.Succeeded}, updateErr
}
// updateStateOnOperationCompletion handles updating/cleaning-up resources that need to be changed
// once lastOperation finishes successfully.
func (gcpBroker *GCPServiceBroker) updateStateOnOperationCompletion(ctx context.Context, service broker.ServiceProvider, lastOperationType, instanceID string) error {
if lastOperationType == models.DeprovisionOperationType {
if err := db_service.DeleteServiceInstanceDetailsById(ctx, instanceID); err != nil {
return fmt.Errorf("Error deleting instance details from database: %s. WARNING: this instance will remain visible in cf. Contact your operator for cleanup", err)
}
return nil
}
// If the operation was not a delete, clear out the ID and type and update
// any changed (or finalized) state like IP addresses, selflinks, etc.
details, err := db_service.GetServiceInstanceDetailsById(ctx, instanceID)
if err != nil {
return fmt.Errorf("Error getting instance details from database %v", err)
}
if err := service.UpdateInstanceDetails(ctx, details); err != nil {
return fmt.Errorf("Error getting new instance details from GCP: %v", err)
}
details.OperationId = ""
details.OperationType = models.ClearOperationType
if err := db_service.SaveServiceInstanceDetails(ctx, details); err != nil {
return fmt.Errorf("Error saving instance details to database %v", err)
}
return nil
}
// Update a service instance plan.
// This functionality is not implemented and will return an error indicating that plan changes are not supported.
func (gcpBroker *GCPServiceBroker) Update(ctx context.Context, instanceID string, details brokerapi.UpdateDetails, asyncAllowed bool) (brokerapi.UpdateServiceSpec, error) {
return brokerapi.UpdateServiceSpec{}, brokerapi.ErrPlanChangeNotSupported
}
func isValidOrEmptyJSON(msg json.RawMessage) bool {
return msg == nil || len(msg) == 0 || json.Valid(msg)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/brokerapi/brokers/broker_config.go | brokerapi/brokers/broker_config.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokers
import (
"fmt"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/brokerpak"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"golang.org/x/oauth2/jwt"
)
type BrokerConfig struct {
HttpConfig *jwt.Config
ProjectId string
Registry broker.BrokerRegistry
}
func NewBrokerConfigFromEnv() (*BrokerConfig, error) {
projectId, err := utils.GetDefaultProjectId()
if err != nil {
return nil, err
}
conf, err := utils.GetAuthedConfig()
if err != nil {
return nil, err
}
registry := builtin.BuiltinBrokerRegistry()
if err := brokerpak.RegisterAll(registry); err != nil {
return nil, fmt.Errorf("Error loading brokerpaks: %v", err)
}
return &BrokerConfig{
ProjectId: projectId,
HttpConfig: conf,
Registry: registry,
}, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/brokerapi/brokers/brokers_test.go | brokerapi/brokers/brokers_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 brokers_test
import (
"context"
"encoding/json"
"errors"
"os"
"reflect"
"testing"
. "github.com/GoogleCloudPlatform/gcp-service-broker/brokerapi/brokers"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker/brokerfakes"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/storage"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"google.golang.org/api/googleapi"
"code.cloudfoundry.org/lager"
"github.com/jinzhu/gorm"
"golang.org/x/oauth2/jwt"
)
// InstanceState holds the lifecycle state of a provisioned service instance.
// It goes None -> Provisioned -> Bound -> Unbound -> Deprovisioned
type InstanceState int
const (
StateNone InstanceState = iota
StateProvisioned
StateBound
StateUnbound
StateDeprovisioned
)
const (
fakeInstanceId = "newid"
fakeBindingId = "newbinding"
)
// serviceStub holds a stubbed out ServiceDefinition with easy access to
// its ID, a valid plan ID, and the mock provider.
type serviceStub struct {
ServiceId string
PlanId string
Provider *brokerfakes.FakeServiceProvider
ServiceDefinition *broker.ServiceDefinition
}
// ProvisionDetails creates a brokerapi.ProvisionDetails object valid for
// the given service.
func (s *serviceStub) ProvisionDetails() brokerapi.ProvisionDetails {
return brokerapi.ProvisionDetails{
ServiceID: s.ServiceId,
PlanID: s.PlanId,
}
}
// DeprovisionDetails creates a brokerapi.DeprovisionDetails object valid for
// the given service.
func (s *serviceStub) DeprovisionDetails() brokerapi.DeprovisionDetails {
return brokerapi.DeprovisionDetails{
ServiceID: s.ServiceId,
PlanID: s.PlanId,
}
}
// BindDetails creates a brokerapi.BindDetails object valid for
// the given service.
func (s *serviceStub) BindDetails() brokerapi.BindDetails {
return brokerapi.BindDetails{
ServiceID: s.ServiceId,
PlanID: s.PlanId,
}
}
// UnbindDetails creates a brokerapi.UnbindDetails object valid for
// the given service.
func (s *serviceStub) UnbindDetails() brokerapi.UnbindDetails {
return brokerapi.UnbindDetails{
ServiceID: s.ServiceId,
PlanID: s.PlanId,
}
}
// fakeService creates a ServiceDefinition with a mock ServiceProvider and
// references to some important properties.
func fakeService(t *testing.T, isAsync bool) *serviceStub {
defn := storage.ServiceDefinition()
svc, err := defn.CatalogEntry()
if err != nil {
t.Fatal(err)
}
stub := serviceStub{
ServiceId: svc.ID,
PlanId: svc.Plans[0].ID,
ServiceDefinition: defn,
Provider: &brokerfakes.FakeServiceProvider{
ProvisionsAsyncStub: func() bool { return isAsync },
DeprovisionsAsyncStub: func() bool { return isAsync },
ProvisionStub: func(ctx context.Context, vc *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
return models.ServiceInstanceDetails{OtherDetails: "{\"mynameis\": \"instancename\"}"}, nil
},
BindStub: func(ctx context.Context, vc *varcontext.VarContext) (map[string]interface{}, error) {
return map[string]interface{}{"foo": "bar"}, nil
},
BuildInstanceCredentialsStub: func(ctx context.Context, bc models.ServiceBindingCredentials, id models.ServiceInstanceDetails) (*brokerapi.Binding, error) {
mixin := base.MergedInstanceCredsMixin{}
return mixin.BuildInstanceCredentials(ctx, bc, id)
},
},
}
stub.ServiceDefinition.ProviderBuilder = func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
return stub.Provider
}
return &stub
}
// newStubbedBroker creates a new GCPServiceBroker with a dummy database for the given registry.
// It returns the broker and a callback used to clean up the database when done with it.
func newStubbedBroker(t *testing.T, registry broker.BrokerRegistry) (broker *GCPServiceBroker, closer func()) {
// Set up database
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
t.Fatalf("couldn't create database: %v", err)
}
db_service.RunMigrations(db)
db_service.DbConnection = db
closer = func() {
db.Close()
os.Remove("test.db")
}
config := &BrokerConfig{
ProjectId: "stub-project",
Registry: registry,
}
broker, err = New(config, utils.NewLogger("brokers-test"))
if err != nil {
t.Fatalf("couldn't create broker: %v", err)
}
return
}
// failIfErr is a test helper function which stops the test immediately if the
// error is set.
func failIfErr(t *testing.T, action string, err error) {
t.Helper()
if err != nil {
t.Fatalf("Expected no error while %s, got: %v", action, err)
}
}
// assertEqual does a reflect.DeepEqual on the values and if they're different
// reports the message and the values.
func assertEqual(t *testing.T, message string, expected, actual interface{}) {
t.Helper()
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Error: %s Expected: %#v Actual: %#v", message, expected, actual)
}
}
// BrokerEndpointTestCase is the base test used for testing any
// brokerapi.ServiceBroker endpoint.
type BrokerEndpointTestCase struct {
// The following properties are used to set up the environment for your test
// to run in.
AsyncService bool
ServiceState InstanceState
// Check is used to validate the state of the world and is where you should
// put your test cases.
Check func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub)
}
// BrokerEndpointTestSuite holds a set of tests for a single endpoint.
type BrokerEndpointTestSuite map[string]BrokerEndpointTestCase
// Run executes every test case, setting up a new environment for each and
// tearing it down afterward.
func (cases BrokerEndpointTestSuite) Run(t *testing.T) {
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
stub := fakeService(t, tc.AsyncService)
t.Log("Creating broker")
registry := broker.BrokerRegistry{}
registry.Register(stub.ServiceDefinition)
broker, closer := newStubbedBroker(t, registry)
defer closer()
initService(t, tc.ServiceState, broker, stub)
t.Log("Running check")
tc.Check(t, broker, stub)
})
}
}
// initService creates a new service and brings it up to the lifecycle state given
// by state.
func initService(t *testing.T, state InstanceState, broker *GCPServiceBroker, stub *serviceStub) {
if state >= StateProvisioned {
_, err := broker.Provision(context.Background(), fakeInstanceId, stub.ProvisionDetails(), true)
failIfErr(t, "provisioning", err)
}
if state >= StateBound {
_, err := broker.Bind(context.Background(), fakeInstanceId, fakeBindingId, stub.BindDetails(), true)
failIfErr(t, "binding", err)
}
if state >= StateUnbound {
_, err := broker.Unbind(context.Background(), fakeInstanceId, fakeBindingId, stub.UnbindDetails(), true)
failIfErr(t, "unbinding", err)
}
if state >= StateDeprovisioned {
_, err := broker.Deprovision(context.Background(), fakeInstanceId, stub.DeprovisionDetails(), true)
failIfErr(t, "deprovisioning", err)
}
}
func TestGCPServiceBroker_Services(t *testing.T) {
registry := builtin.BuiltinBrokerRegistry()
broker, closer := newStubbedBroker(t, registry)
defer closer()
services, err := broker.Services(context.Background())
failIfErr(t, "getting services", err)
assertEqual(t, "service count should be the same", len(registry), len(services))
}
func TestGCPServiceBroker_Provision(t *testing.T) {
cases := BrokerEndpointTestSuite{
"good-request": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
assertEqual(t, "provision calls should match", 1, stub.Provider.ProvisionCallCount())
},
},
"duplicate-request": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Provision(context.Background(), fakeInstanceId, stub.ProvisionDetails(), true)
assertEqual(t, "errors should match", brokerapi.ErrInstanceAlreadyExists, err)
},
},
"requires-async": {
AsyncService: true,
ServiceState: StateNone,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
// false for async support
_, err := broker.Provision(context.Background(), fakeInstanceId, stub.ProvisionDetails(), false)
assertEqual(t, "errors should match", brokerapi.ErrAsyncRequired, err)
},
},
"unknown-service-id": {
ServiceState: StateNone,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
req := stub.ProvisionDetails()
req.ServiceID = "bad-service-id"
_, err := broker.Provision(context.Background(), fakeInstanceId, req, true)
assertEqual(t, "errors should match", errors.New("Unknown service ID: \"bad-service-id\""), err)
},
},
"unknown-plan-id": {
ServiceState: StateNone,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
req := stub.ProvisionDetails()
req.PlanID = "bad-plan-id"
_, err := broker.Provision(context.Background(), fakeInstanceId, req, true)
assertEqual(t, "errors should match", errors.New("Plan ID \"bad-plan-id\" could not be found"), err)
},
},
"bad-request-json": {
ServiceState: StateNone,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
req := stub.ProvisionDetails()
req.RawParameters = json.RawMessage("{invalid json")
_, err := broker.Provision(context.Background(), fakeInstanceId, req, true)
assertEqual(t, "errors should match", ErrInvalidUserInput, err)
},
},
}
cases.Run(t)
}
func TestGCPServiceBroker_Deprovision(t *testing.T) {
cases := BrokerEndpointTestSuite{
"good-request": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Deprovision(context.Background(), fakeInstanceId, stub.DeprovisionDetails(), true)
failIfErr(t, "deprovisioning", err)
assertEqual(t, "deprovision calls should match", 1, stub.Provider.DeprovisionCallCount())
},
},
"duplicate-deprovision": {
ServiceState: StateDeprovisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Deprovision(context.Background(), fakeInstanceId, stub.DeprovisionDetails(), true)
assertEqual(t, "duplicate deprovision should lead to DNE", brokerapi.ErrInstanceDoesNotExist, err)
},
},
"instance-does-not-exist": {
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Deprovision(context.Background(), fakeInstanceId, stub.DeprovisionDetails(), true)
assertEqual(t, "instance does not exist should be set", brokerapi.ErrInstanceDoesNotExist, err)
},
},
"async-required": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Deprovision(context.Background(), fakeInstanceId, stub.DeprovisionDetails(), false)
assertEqual(t, "async required should be returned if not supported", brokerapi.ErrAsyncRequired, err)
},
},
"async-deprovision-returns-operation": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
operationId := "my-operation-id"
stub.Provider.DeprovisionReturns(&operationId, nil)
resp, err := broker.Deprovision(context.Background(), fakeInstanceId, stub.DeprovisionDetails(), true)
failIfErr(t, "deprovisioning", err)
assertEqual(t, "operationid should be set as the data", operationId, resp.OperationData)
assertEqual(t, "IsAsync should be set", true, resp.IsAsync)
},
},
"async-deprovision-updates-db": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
operationId := "my-operation-id"
stub.Provider.DeprovisionReturns(&operationId, nil)
_, err := broker.Deprovision(context.Background(), fakeInstanceId, stub.DeprovisionDetails(), true)
failIfErr(t, "deprovisioning", err)
details, err := db_service.GetServiceInstanceDetailsById(context.Background(), fakeInstanceId)
failIfErr(t, "looking up details", err)
assertEqual(t, "OperationId should be set as the data", operationId, details.OperationId)
assertEqual(t, "OperationType should be set as Deprovision", models.DeprovisionOperationType, details.OperationType)
},
},
}
cases.Run(t)
}
func TestGCPServiceBroker_Bind(t *testing.T) {
cases := BrokerEndpointTestSuite{
"good-request": {
ServiceState: StateBound,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
assertEqual(t, "BindCallCount should match", 1, stub.Provider.BindCallCount())
assertEqual(t, "BuildInstanceCredentialsCallCount should match", 1, stub.Provider.BuildInstanceCredentialsCallCount())
},
},
"duplicate-request": {
ServiceState: StateBound,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Bind(context.Background(), fakeInstanceId, fakeBindingId, stub.BindDetails(), true)
assertEqual(t, "errors should match", brokerapi.ErrBindingAlreadyExists, err)
},
},
"bad-bind-call": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
req := stub.BindDetails()
req.RawParameters = json.RawMessage(`{"role":"project.admin"}`)
expectedErr := "1 error(s) occurred: role: role must be one of the following: \"storage.objectAdmin\", \"storage.objectCreator\", \"storage.objectViewer\""
_, err := broker.Bind(context.Background(), fakeInstanceId, "bad-bind-call", req, true)
assertEqual(t, "errors should match", expectedErr, err.Error())
},
},
"bad-request-json": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
req := stub.BindDetails()
req.RawParameters = json.RawMessage("{invalid json")
_, err := broker.Bind(context.Background(), fakeInstanceId, fakeBindingId, req, true)
assertEqual(t, "errors should match", ErrInvalidUserInput, err)
},
},
}
cases.Run(t)
}
func TestGCPServiceBroker_Unbind(t *testing.T) {
cases := BrokerEndpointTestSuite{
"good-request": {
ServiceState: StateBound,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Unbind(context.Background(), fakeInstanceId, fakeBindingId, stub.UnbindDetails(), true)
failIfErr(t, "unbinding", err)
},
},
"multiple-unbinds": {
ServiceState: StateUnbound,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.Unbind(context.Background(), fakeInstanceId, fakeBindingId, stub.UnbindDetails(), true)
assertEqual(t, "errors should match", brokerapi.ErrBindingDoesNotExist, err)
},
},
}
cases.Run(t)
}
func TestGCPServiceBroker_LastOperation(t *testing.T) {
cases := BrokerEndpointTestSuite{
"missing-instance": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.LastOperation(context.Background(), "invalid-instance-id", brokerapi.PollDetails{OperationData: "operationtoken"})
assertEqual(t, "errors should match", brokerapi.ErrInstanceDoesNotExist, err)
},
},
"called-on-synchronous-service": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.LastOperation(context.Background(), fakeInstanceId, brokerapi.PollDetails{OperationData: "operationtoken"})
assertEqual(t, "errors should match", brokerapi.ErrAsyncRequired, err)
},
},
"called-on-async-service": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.LastOperation(context.Background(), fakeInstanceId, brokerapi.PollDetails{OperationData: "operationtoken"})
failIfErr(t, "shouldn't be called on async service", err)
assertEqual(t, "PollInstanceCallCount should match", 1, stub.Provider.PollInstanceCallCount())
},
},
"poll-returns-retryable-error": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
stub.Provider.PollInstanceReturns(false, &googleapi.Error{Code: 503})
status, _ := broker.LastOperation(context.Background(), fakeInstanceId, brokerapi.PollDetails{OperationData: "operationtoken"})
assertEqual(t, "retryable errors should result in in-progress state", brokerapi.InProgress, status.State)
},
},
"poll-returns-failure": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
stub.Provider.PollInstanceReturns(false, errors.New("not-retryable"))
status, _ := broker.LastOperation(context.Background(), fakeInstanceId, brokerapi.PollDetails{OperationData: "operationtoken"})
assertEqual(t, "non-retryable errors should result in a failure state", brokerapi.Failed, status.State)
},
},
"poll-returns-not-done": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
stub.Provider.PollInstanceReturns(false, nil)
status, err := broker.LastOperation(context.Background(), fakeInstanceId, brokerapi.PollDetails{OperationData: "operationtoken"})
failIfErr(t, "checking last operation", err)
assertEqual(t, "polls that return no error should result in an in-progress state", brokerapi.InProgress, status.State)
},
},
"poll-returns-success": {
AsyncService: true,
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
stub.Provider.PollInstanceReturns(true, nil)
status, err := broker.LastOperation(context.Background(), fakeInstanceId, brokerapi.PollDetails{OperationData: "operationtoken"})
failIfErr(t, "checking last operation", err)
assertEqual(t, "polls that return finished should result in a succeeded state", brokerapi.Succeeded, status.State)
},
},
}
cases.Run(t)
}
func TestGCPServiceBroker_GetBinding(t *testing.T) {
cases := BrokerEndpointTestSuite{
"called-on-bound": {
ServiceState: StateBound,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.GetBinding(context.Background(), fakeInstanceId, fakeBindingId)
assertEqual(t, "expect get binding not supported err", ErrGetBindingsUnsupported, err)
},
},
}
cases.Run(t)
}
func TestGCPServiceBroker_GetInstance(t *testing.T) {
cases := BrokerEndpointTestSuite{
"called-while-provisioned": {
ServiceState: StateProvisioned,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.GetInstance(context.Background(), fakeInstanceId)
assertEqual(t, "expect get instances not supported err", ErrGetInstancesUnsupported, err)
},
},
}
cases.Run(t)
}
func TestGCPServiceBroker_LastBindingOperation(t *testing.T) {
cases := BrokerEndpointTestSuite{
"called-while-bound": {
ServiceState: StateProvisioned,
AsyncService: true,
Check: func(t *testing.T, broker *GCPServiceBroker, stub *serviceStub) {
_, err := broker.LastBindingOperation(context.Background(), fakeInstanceId, fakeBindingId, brokerapi.PollDetails{})
assertEqual(t, "expect last binding to return async required", brokerapi.ErrAsyncRequired, err)
},
},
}
cases.Run(t)
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/utils.go | utils/utils.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 utils
import (
"encoding/json"
"fmt"
"log"
"os"
"regexp"
"strings"
"code.cloudfoundry.org/lager"
"github.com/pivotal-cf/brokerapi"
"github.com/spf13/viper"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
)
const (
EnvironmentVarPrefix = "gsb"
rootSaEnvVar = "ROOT_SERVICE_ACCOUNT_JSON"
cloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
)
var (
PropertyToEnvReplacer = strings.NewReplacer(".", "_", "-", "_")
// GCP labels only support alphanumeric, dash and underscore characters in
// keys and values.
invalidLabelChars = regexp.MustCompile("[^a-zA-Z0-9_-]+")
)
func init() {
viper.BindEnv("google.account", rootSaEnvVar)
}
func GetAuthedConfig() (*jwt.Config, error) {
rootCreds := GetServiceAccountJson()
conf, err := google.JWTConfigFromJSON([]byte(rootCreds), cloudPlatformScope)
if err != nil {
return nil, fmt.Errorf("Error initializing config from credentials: %s", err)
}
return conf, nil
}
// PrettyPrintOrExit writes a JSON serialized version of the content to stdout.
// If a failure occurs during marshaling, the error is logged along with a
// formatted version of the object and the program exits with a failure status.
func PrettyPrintOrExit(content interface{}) {
err := prettyPrint(content)
if err != nil {
log.Fatalf("Could not format results: %s, results were: %+v", err, content)
}
}
// PrettyPrintOrErr writes a JSON serialized version of the content to stdout.
// If a failure occurs during marshaling, the error is logged along with a
// formatted version of the object and the function will return the error.
func PrettyPrintOrErr(content interface{}) error {
err := prettyPrint(content)
if err != nil {
log.Printf("Could not format results: %s, results were: %+v", err, content)
}
return err
}
func prettyPrint(content interface{}) error {
prettyResults, err := json.MarshalIndent(content, "", " ")
if err == nil {
fmt.Println(string(prettyResults))
}
return err
}
// PropertyToEnv converts a Viper configuration property name into an
// environment variable prefixed with EnvironmentVarPrefix
func PropertyToEnv(propertyName string) string {
return PropertyToEnvUnprefixed(EnvironmentVarPrefix + "." + propertyName)
}
// PropertyToEnvUnprefixed converts a Viper configuration property name into an
// environment variable using PropertyToEnvReplacer
func PropertyToEnvUnprefixed(propertyName string) string {
return PropertyToEnvReplacer.Replace(strings.ToUpper(propertyName))
}
// SetParameter sets a value on a JSON raw message and returns a modified
// version with the value set
func SetParameter(input json.RawMessage, key string, value interface{}) (json.RawMessage, error) {
params := make(map[string]interface{})
if input != nil && len(input) != 0 {
err := json.Unmarshal(input, ¶ms)
if err != nil {
return nil, err
}
}
params[key] = value
return json.Marshal(params)
}
// UnmarshalObjectRemaidner unmarshals an object into v and returns the
// remaining key/value pairs as a JSON string by doing a set difference.
func UnmarshalObjectRemainder(data []byte, v interface{}) ([]byte, error) {
if err := json.Unmarshal(data, v); err != nil {
return nil, err
}
encoded, err := json.Marshal(v)
if err != nil {
return nil, err
}
return jsonDiff(data, encoded)
}
func jsonDiff(superset, subset json.RawMessage) ([]byte, error) {
usedKeys := make(map[string]json.RawMessage)
if err := json.Unmarshal(subset, &usedKeys); err != nil {
return nil, err
}
allKeys := make(map[string]json.RawMessage)
if err := json.Unmarshal(superset, &allKeys); err != nil {
return nil, err
}
remainder := make(map[string]json.RawMessage)
for key, value := range allKeys {
if _, ok := usedKeys[key]; !ok {
remainder[key] = value
}
}
return json.Marshal(remainder)
}
// GetDefaultProject gets the default project id for the service broker based
// on the JSON Service Account key.
func GetDefaultProjectId() (string, error) {
serviceAccount := make(map[string]string)
if err := json.Unmarshal([]byte(GetServiceAccountJson()), &serviceAccount); err != nil {
return "", fmt.Errorf("could not unmarshal service account details. %v", err)
}
return serviceAccount["project_id"], nil
}
// GetServiceAccountJson gets the raw JSON credentials of the Service Account
// the service broker acts as.
func GetServiceAccountJson() string {
return viper.GetString("google.account")
}
// ExtractDefaultLabels creates a map[string]string of labels that should be
// applied to a resource on creation if the resource supports labels.
// These include the organization, space, and instance id.
func ExtractDefaultLabels(instanceId string, details brokerapi.ProvisionDetails) map[string]string {
labels := map[string]string{
"pcf-organization-guid": details.OrganizationGUID,
"pcf-space-guid": details.SpaceGUID,
"pcf-instance-id": instanceId,
}
// After v 2.14 of the OSB the top-level organization_guid and space_guid are
// deprecated in favor of context, so we'll override those.
requestContext := map[string]string{}
json.Unmarshal(details.GetRawContext(), &requestContext) // explicitly ignore parse errors
if orgGuid, ok := requestContext["organization_guid"]; ok {
labels["pcf-organization-guid"] = orgGuid
}
if spaceGuid, ok := requestContext["space_guid"]; ok {
labels["pcf-space-guid"] = spaceGuid
}
sanitized := map[string]string{}
for key, value := range labels {
sanitized[key] = invalidLabelChars.ReplaceAllString(value, "_")
}
return sanitized
}
// SingleLineErrorFormatter creates a single line error string from an array of errors.
func SingleLineErrorFormatter(es []error) string {
points := make([]string, len(es))
for i, err := range es {
points[i] = err.Error()
}
return fmt.Sprintf("%d error(s) occurred: %s", len(es), strings.Join(points, "; "))
}
// NewLogger creates a new lager.Logger with the given name that has correct
// writing settings.
func NewLogger(name string) lager.Logger {
logger := lager.NewLogger(name)
logger.RegisterSink(lager.NewWriterSink(os.Stderr, lager.ERROR))
logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))
return logger
}
// SplitNewlineDelimitedList splits a list of newline delimited items and trims
// any leading or trailing whitespace from them.
func SplitNewlineDelimitedList(paksText string) []string {
var out []string
for _, pak := range strings.Split(paksText, "\n") {
pakUrl := strings.TrimSpace(pak)
if pakUrl != "" {
out = append(out, pakUrl)
}
}
return out
}
// Indent indents every line of the given text with the given string.
func Indent(text, by string) string {
lines := strings.Split(text, "\n")
for i, line := range lines {
lines[i] = by + line
}
return strings.Join(lines, "\n")
}
// CopyStringMap makes a copy of the given map.
func CopyStringMap(m map[string]string) map[string]string {
out := make(map[string]string)
for k, v := range m {
out[k] = v
}
return out
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/set_test.go | utils/set_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 utils
import "fmt"
func ExampleStringSet_Add() {
set := NewStringSet()
set.Add("a")
set.Add("b")
fmt.Println(set)
set.Add("a")
fmt.Println(set)
// Output: [a b]
// [a b]
}
func ExampleNewStringSet() {
a := NewStringSet()
a.Add("a")
a.Add("b")
b := NewStringSet("b", "a")
fmt.Println(a.Equals(b))
// Output: true
}
func ExampleNewStringSetFromStringMapKeys() {
m := map[string]string{
"a": "some a value",
"b": "some b value",
}
set := NewStringSetFromStringMapKeys(m)
fmt.Println(set)
// Output: [a b]
}
func ExampleStringSet_ToSlice() {
a := NewStringSet()
a.Add("z")
a.Add("b")
fmt.Println(a.ToSlice())
// Output: [b z]
}
func ExampleStringSet_IsEmpty() {
a := NewStringSet()
fmt.Println(a.IsEmpty())
a.Add("a")
fmt.Println(a.IsEmpty())
// Output: true
// false
}
func ExampleStringSet_Equals() {
a := NewStringSet("a", "b")
b := NewStringSet("a", "b", "c")
fmt.Println(a.Equals(b))
a.Add("c")
fmt.Println(a.Equals(b))
// Output: false
// true
}
func ExampleStringSet_Contains() {
a := NewStringSet("a", "b")
fmt.Println(a.Contains("z"))
fmt.Println(a.Contains("a"))
// Output: false
// true
}
func ExampleStringSet_Minus() {
a := NewStringSet("a", "b")
b := NewStringSet("b", "c")
delta := a.Minus(b)
fmt.Println(delta)
// Output: [a]
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/utils_test.go | utils/utils_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 utils
import (
"encoding/json"
"fmt"
"os"
"reflect"
"testing"
"github.com/pivotal-cf/brokerapi"
)
func ExamplePropertyToEnv() {
env := PropertyToEnv("my.property.key-value")
fmt.Println(env)
// Output: GSB_MY_PROPERTY_KEY_VALUE
}
func ExamplePropertyToEnvUnprefixed() {
env := PropertyToEnvUnprefixed("my.property.key-value")
fmt.Println(env)
// Output: MY_PROPERTY_KEY_VALUE
}
func ExampleSetParameter() {
// Creates an object if none is input
out, err := SetParameter(nil, "foo", 42)
fmt.Printf("%s, %v\n", string(out), err)
// Replaces existing values
out, err = SetParameter([]byte(`{"replace": "old"}`), "replace", "new")
fmt.Printf("%s, %v\n", string(out), err)
// Output: {"foo":42}, <nil>
// {"replace":"new"}, <nil>
}
func ExampleUnmarshalObjectRemainder() {
var obj struct {
A string `json:"a_str"`
B int
}
remainder, err := UnmarshalObjectRemainder([]byte(`{"a_str":"hello", "B": 33, "C": 123}`), &obj)
fmt.Printf("%s, %v\n", string(remainder), err)
remainder, err = UnmarshalObjectRemainder([]byte(`{"a_str":"hello", "B": 33}`), &obj)
fmt.Printf("%s, %v\n", string(remainder), err)
// Output: {"C":123}, <nil>
// {}, <nil>
}
func ExampleGetDefaultProjectId() {
serviceAccountJson := `{
"//": "Dummy account from https://github.com/GoogleCloudPlatform/google-cloud-java/google-cloud-clients/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java",
"private_key_id": "somekeyid",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC+K2hSuFpAdrJI\nnCgcDz2M7t7bjdlsadsasad+fvRSW6TjNQZ3p5LLQY1kSZRqBqylRkzteMOyHgaR\n0Pmxh3ILCND5men43j3h4eDbrhQBuxfEMalkG92sL+PNQSETY2tnvXryOvmBRwa/\nQP/9dJfIkIDJ9Fw9N4Bhhhp6mCcRpdQjV38H7JsyJ7lih/oNjECgYAt\nknddadwkwewcVxHFhcZJO+XWf6ofLUXpRwiTZakGMn8EE1uVa2LgczOjwWHGi99MFjxSer5m9\n1tCa3/KEGKiS/YL71JvjwX3mb+cewlkcmweBKZHM2JPTk0ZednFSpVZMtycjkbLa\ndYOS8V85AgMBewECggEBAKksaldajfDZDV6nGqbFjMiizAKJolr/M3OQw16K6o3/\n0S31xIe3sSlgW0+UbYlF4U8KifhManD1apVSC3csafaspP4RZUHFhtBywLO9pR5c\nr6S5aLp+gPWFyIp1pfXbWGvc5VY/v9x7ya1VEa6rXvLsKupSeWAW4tMj3eo/64ge\nsdaceaLYw52KeBYiT6+vpsnYrEkAHO1fF/LavbLLOFJmFTMxmsNaG0tuiJHgjshB\n82DpMCbXG9YcCgI/DbzuIjsdj2JC1cascSP//3PmefWysucBQe7Jryb6NQtASmnv\nCdDw/0jmZTEjpe4S1lxfHplAhHFtdgYTvyYtaLZiVVkCgYEA8eVpof2rceecw/I6\n5ng1q3Hl2usdWV/4mZMvR0fOemacLLfocX6IYxT1zA1FFJlbXSRsJMf/Qq39mOR2\nSpW+hr4jCoHeRVYLgsbggtrevGmILAlNoqCMpGZ6vDmJpq6ECV9olliDvpPgWOP+\nmYPDreFBGxWvQrADNbRt2dmGsrsCgYEAyUHqB2wvJHFqdmeBsaacewzV8x9WgmeX\ngUIi9REwXlGDW0Mz50dxpxcKCAYn65+7TCnY5O/jmL0VRxU1J2mSWyWTo1C+17L0\n3fUqjxL1pkefwecxwecvC+gFFYdJ4CQ/MHHXU81Lwl1iWdFCd2UoGddYaOF+KNeM\nHC7cmqra+JsCgYEAlUNywzq8nUg7282E+uICfCB0LfwejuymR93CtsFgb7cRd6ak\nECR8FGfCpH8ruWJINllbQfcHVCX47ndLZwqv3oVFKh6pAS/vVI4dpOepP8++7y1u\ncoOvtreXCX6XqfrWDtKIvv0vjlHBhhhp6mCcRpdQjV38H7JsyJ7lih/oNjECgYAt\nkndj5uNl5SiuVxHFhcZJO+XWf6ofLUregtevZakGMn8EE1uVa2AY7eafmoU/nZPT\n00YB0TBATdCbn/nBSuKDESkhSg9s2GEKQZG5hBmL5uCMfo09z3SfxZIhJdlerreP\nJ7gSidI12N+EZxYd4xIJh/HFDgp7RRO87f+WJkofMQKBgGTnClK1VMaCRbJZPriw\nEfeFCoOX75MxKwXs6xgrw4W//AYGGUjDt83lD6AZP6tws7gJ2IwY/qP7+lyhjEqN\nHtfPZRGFkGZsdaksdlaksd323423d+15/UvrlRSFPNj1tWQmNKkXyRDW4IG1Oa2p\nrALStNBx5Y9t0/LQnFI4w3aG\n-----END PRIVATE KEY-----\n",
"client_email": "someclientid@developer.gserviceaccount.com",
"client_id": "someclientid.apps.googleusercontent.com",
"type": "service_account",
"project_id": "my-project-123"
}`
os.Setenv("ROOT_SERVICE_ACCOUNT_JSON", serviceAccountJson)
defer os.Unsetenv("ROOT_SERVICE_ACCOUNT_JSON")
projectId, err := GetDefaultProjectId()
fmt.Printf("%s, %v\n", projectId, err)
// Output: my-project-123, <nil>
}
func TestExtractDefaultLabels(t *testing.T) {
tests := map[string]struct {
instanceId string
details brokerapi.ProvisionDetails
expected map[string]string
}{
"empty everything": {
instanceId: "",
details: brokerapi.ProvisionDetails{},
expected: map[string]string{
"pcf-organization-guid": "",
"pcf-space-guid": "",
"pcf-instance-id": "",
},
},
"osb 2.13": {
instanceId: "my-instance",
details: brokerapi.ProvisionDetails{OrganizationGUID: "org-guid", SpaceGUID: "space-guid"},
expected: map[string]string{
"pcf-organization-guid": "org-guid",
"pcf-space-guid": "space-guid",
"pcf-instance-id": "my-instance",
},
},
"osb future": {
instanceId: "my-instance",
details: brokerapi.ProvisionDetails{
OrganizationGUID: "org-guid",
SpaceGUID: "space-guid",
RawContext: json.RawMessage(`{"organization_guid":"org-override", "space_guid":"space-override"}`),
},
expected: map[string]string{
"pcf-organization-guid": "org-override",
"pcf-space-guid": "space-override",
"pcf-instance-id": "my-instance",
},
},
"osb special characters": {
instanceId: "my~instance.",
details: brokerapi.ProvisionDetails{},
expected: map[string]string{
"pcf-organization-guid": "",
"pcf-space-guid": "",
"pcf-instance-id": "my_instance_",
},
},
}
for tn, tc := range tests {
labels := ExtractDefaultLabels(tc.instanceId, tc.details)
if !reflect.DeepEqual(labels, tc.expected) {
t.Errorf("Error runniung case %q, expected: %v got: %v", tn, tc.expected, labels)
}
}
}
func TestSplitNewlineDelimitedList(t *testing.T) {
cases := map[string]struct {
Input string
Expected []string
}{
"none": {
Input: ``,
Expected: nil,
},
"single": {
Input: `gs://foo/bar`,
Expected: []string{"gs://foo/bar"},
},
"crlf": {
Input: "a://foo\r\nb://bar",
Expected: []string{"a://foo", "b://bar"},
},
"trim": {
Input: " a://foo \n\tb://bar ",
Expected: []string{"a://foo", "b://bar"},
},
"blank": {
Input: "\n\r\r\n\n\t\t\v\n\n\n\n\n \n\n\n \n \n \n\n",
Expected: nil,
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := SplitNewlineDelimitedList(tc.Input)
if !reflect.DeepEqual(tc.Expected, actual) {
t.Errorf("Expected: %v actual: %v", tc.Expected, actual)
}
})
}
}
func ExampleIndent() {
weirdText := "First\n\tSecond"
out := Indent(weirdText, " ")
fmt.Println(out == " First\n \tSecond")
// Output: true
}
func ExampleCopyStringMap() {
m := map[string]string{"a": "one"}
copy := CopyStringMap(m)
m["a"] = "two"
fmt.Println(m["a"])
fmt.Println(copy["a"])
// Output: two
// one
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/set.go | utils/set.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 utils
import (
"fmt"
"reflect"
"sort"
)
// NewStringSet creates a new string set with the given contents.
func NewStringSet(contents ...string) StringSet {
set := StringSet{}
set.Add(contents...)
return set
}
// NewStringSet creates a new string set with the given contents.
func NewStringSetFromStringMapKeys(contents map[string]string) StringSet {
set := StringSet{}
for k, _ := range contents {
set.Add(k)
}
return set
}
// StringSet is a set data structure for strings
type StringSet map[string]bool
// Add puts one or more elements into the set.
func (set StringSet) Add(str ...string) {
for _, s := range str {
set[s] = true
}
}
// ToSlice converts the set to a slice with sort.Strings order.
func (set StringSet) ToSlice() []string {
out := []string{}
for k := range set {
out = append(out, k)
}
sort.Strings(out)
return out
}
// IsEmpty determines if the set has zero elements.
func (set StringSet) IsEmpty() bool {
return len(set) == 0
}
// Equals compares the contents of the two sets and returns true if they are
// the same.
func (set StringSet) Equals(other StringSet) bool {
return reflect.DeepEqual(set, other)
}
// Contains performs a set membership check.
func (set StringSet) Contains(other string) bool {
_, ok := set[other]
return ok
}
// Returns a copy of this set with every string in the other removed.
func (set StringSet) Minus(other StringSet) StringSet {
difference := NewStringSet()
for k, _ := range set {
if !other.Contains(k) {
difference.Add(k)
}
}
return difference
}
// String converts this set to a human readable string.
func (set StringSet) String() string {
return fmt.Sprintf("%v", set.ToSlice())
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/version.go | utils/version.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 utils
// Version sets the version for the whole GCP service broker software.
const Version = "5.1.0"
// This custom user agent string is added to provision calls so that Google can track the aggregated use of this tool
// We can better advocate for devoting resources to supporting cloud foundry and this service broker if we can show
// good usage statistics for it, so if you feel the need to fork this repo, please leave this string in place!
const CustomUserAgent = "cf-gcp-service-broker " + Version
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/stream/stream.go | utils/stream/stream.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 stream
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sync"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
multierror "github.com/hashicorp/go-multierror"
yaml "gopkg.in/yaml.v2"
)
type Source func() (io.ReadCloser, error)
type Dest func() (io.WriteCloser, error)
// Copy copies data from a source stream to a destination stream.
func Copy(src Source, dest Dest) error {
mc := MultiCloser{}
defer mc.Close()
readCloser, err := src()
if err != nil {
return fmt.Errorf("copy couldn't open source: %v", err)
}
mc.Add(readCloser)
writeCloser, err := dest()
if err != nil {
return fmt.Errorf("copy couldn't open destination: %v", err)
}
mc.Add(writeCloser)
if _, err := io.Copy(writeCloser, readCloser); err != nil {
return fmt.Errorf("copy couldn't copy data: %v", err)
}
if err := mc.Close(); err != nil {
return fmt.Errorf("copy couldn't close streams: %v", err)
}
return nil
}
// FromYaml converts the interface to a stream of Yaml.
func FromYaml(v interface{}) Source {
bytes, err := yaml.Marshal(v)
if err != nil {
return FromError(err)
}
return FromBytes(bytes)
}
// FromBytes streams the given bytes as a buffer.
func FromBytes(b []byte) Source {
return FromReader(bytes.NewReader(b))
}
// FromBytes streams the given bytes as a buffer.
func FromString(s string) Source {
return FromBytes([]byte(s))
}
// FromError returns a nil ReadCloser and the error passed when called.
func FromError(err error) Source {
return func() (io.ReadCloser, error) {
return nil, err
}
}
// FromFile joins the segments of the path and reads from it.
func FromFile(path ...string) Source {
return FromReadCloserError(os.Open(filepath.Join(path...)))
}
// FromReadCloserError reads the contents of the readcloser and takes ownership of closing it.
// If err is non-nil, it is returned as a source.
func FromReadCloserError(rc io.ReadCloser, err error) Source {
return func() (io.ReadCloser, error) {
return rc, err
}
}
// FromReadCloser reads the contents of the readcloser and takes ownership of closing it.
func FromReadCloser(rc io.ReadCloser) Source {
return FromReadCloserError(rc, nil)
}
// FromReader converts a Reader to a Source.
func FromReader(rc io.Reader) Source {
return func() (io.ReadCloser, error) {
return ioutil.NopCloser(rc), nil
}
}
// ToFile concatenates the given path segments with filepath.Join, creates any
// parent directoreis if needed, and writes the file.
func ToFile(path ...string) Dest {
return ToModeFile(0600, path...)
}
// ToModeFile is like ToFile, but sets the permissions on the created file.
func ToModeFile(mode os.FileMode, path ...string) Dest {
return func() (io.WriteCloser, error) {
outputPath := filepath.Join(path...)
if err := os.MkdirAll(filepath.Dir(outputPath), 0700|os.ModeDir); err != nil {
return nil, err
}
return os.OpenFile(outputPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
}
}
// ToBuffer buffers the contents of the stream and on Close() calls the callback
// returning its error.
func ToBuffer(closeCallback func(*bytes.Buffer) error) Dest {
return func() (io.WriteCloser, error) {
return &bufferCallback{closeCallback: closeCallback}, nil
}
}
// ToYaml unmarshals the contents of the stream as YAML to the given struct.
func ToYaml(v interface{}) Dest {
return ToBuffer(func(buf *bytes.Buffer) error {
return yaml.Unmarshal(buf.Bytes(), v)
})
}
// ToError returns an error when Dest is initialized.
func ToError(err error) Dest {
return func() (io.WriteCloser, error) {
return nil, err
}
}
// ToDiscard discards any data written to it.
func ToDiscard() Dest {
return ToWriter(ioutil.Discard)
}
// ToWriter forwards data to the given writer, this function WILL NOT close the
// underlying stream so it is safe to use with things like stdout.
func ToWriter(writer io.Writer) Dest {
return ToWriteCloser(NopWriteCloser(writer))
}
// ToWriteCloser forwards data to the given WriteCloser which will be closed
// after the copy finishes.
func ToWriteCloser(w io.WriteCloser) Dest {
return func() (io.WriteCloser, error) {
return w, nil
}
}
// bufferCallback buffers the results and on close calls the callback.
type bufferCallback struct {
bytes.Buffer
closeCallback func(*bytes.Buffer) error
}
// Close implements io.Closer.
func (b *bufferCallback) Close() error {
return b.closeCallback(&b.Buffer)
}
// NopWriteCloser works like io.NopCloser, but for writers.
func NopWriteCloser(w io.Writer) io.WriteCloser {
return errWriteCloser{Writer: w, CloseErr: nil}
}
type errWriteCloser struct {
io.Writer
CloseErr error
}
// Close implements io.Closer.
func (w errWriteCloser) Close() error {
return w.CloseErr
}
// MultiCloser calls Close() once on every added closer and returns
// a multierror of all errors encountered.
type MultiCloser struct {
closers []io.Closer
mu sync.Mutex
}
// Add appends the closer to the internal list of closers.
func (mc *MultiCloser) Add(c io.Closer) {
mc.mu.Lock()
defer mc.mu.Unlock()
mc.closers = append(mc.closers, c)
}
// Close calls close on all closers, discarding them from the list.
// Modifying MultiCloser in your Close method will create a deadlock.
// At the end of this function, the close list will be empty and any encountered
// errors will be returned.
func (mc *MultiCloser) Close() error {
mc.mu.Lock()
defer mc.mu.Unlock()
result := &multierror.Error{ErrorFormat: utils.SingleLineErrorFormatter}
for _, closer := range mc.closers {
if err := closer.Close(); err != nil {
result = multierror.Append(result, err)
}
}
mc.closers = []io.Closer{}
return result.ErrorOrNil()
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/stream/stream_test.go | utils/stream/stream_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 stream
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"testing"
)
func TestBufferCallback_Write(t *testing.T) {
writer := bufferCallback{}
writer.Write([]byte("hello, world!"))
if !reflect.DeepEqual(writer.Bytes(), []byte("hello, world!")) {
t.Fatalf("write didn't append to the buffer")
}
}
func TestBufferCallback_Close(t *testing.T) {
testErr := errors.New("test error")
calledBack := false
writer := bufferCallback{
closeCallback: func(b *bytes.Buffer) error {
calledBack = true
return testErr
},
}
closeErr := writer.Close()
if !calledBack {
t.Errorf("Callback not called on close!")
}
if testErr != closeErr {
t.Fatalf("expected err %v got %v", testErr, closeErr)
}
}
func TestCopy(t *testing.T) {
cases := map[string]struct {
src Source
dest Dest
expected error
}{
"Source Init Err": {
src: FromError(errors.New("srcerr")),
dest: ToDiscard(),
expected: errors.New("copy couldn't open source: srcerr"),
},
"Dest Init Err": {
src: FromString(""),
dest: ToError(errors.New("desterr")),
expected: errors.New("copy couldn't open destination: desterr"),
},
"Dest Close Err": {
src: FromString(""),
dest: func() (io.WriteCloser, error) {
return errWriteCloser{ioutil.Discard, errors.New("closerr")}, nil
},
expected: errors.New("copy couldn't close streams: 1 error(s) occurred: closerr"),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
err := Copy(tc.src, tc.dest)
if err.Error() != tc.expected.Error() {
t.Fatalf("expected error: '%v' got '%v'", tc.expected, err)
}
})
}
}
func ExampleYaml() {
type Test struct {
Str string `yaml:"s"`
Num int `yaml:"i"`
}
a := Test{"foo", 42}
b := Test{}
err := Copy(FromYaml(a), ToYaml(&b))
if err != nil {
panic(err)
}
fmt.Printf("%#v", b)
// Output: stream.Test{Str:"foo", Num:42}
}
func ExampleFile() {
td, err := ioutil.TempDir("", "test")
if err != nil {
panic(err)
}
defer os.RemoveAll(td)
Copy(FromString("hello\nworld"), ToFile(td, "parent", "other", "testing.txt"))
fullpath := filepath.Join(td, "parent", "other", "testing.txt")
Copy(FromFile(fullpath), ToWriter(os.Stdout))
// Output: hello
// world
}
func ExampleMultiCloser() {
var mc MultiCloser
mc.Add(ioutil.NopCloser(nil))
fmt.Println("closed:", mc.Close())
// Output: closed: <nil>
}
func ExampleMultiCloser_Error() {
var mc MultiCloser
closer := errWriteCloser{nil, errors.New("example close error")}
mc.Add(closer)
fmt.Println("error closed:", mc.Close())
fmt.Println("call after closed:", mc.Close())
// Output: error closed: 1 error(s) occurred: example close error
// call after closed: <nil>
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/ziputil/zip_test.go | utils/ziputil/zip_test.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 ziputil
import (
"archive/zip"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/stream"
)
// A zip file with a single file with the contents "Hello, world!":
// MODE SIZE NAME
// -rw-rw-rw- 13 path/to/my/file.txt
var exampleFile = []byte{
0x50, 0x4b, 0x3, 0x4, 0x14, 0x0, 0x8, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x13, 0x0,
0x0, 0x0, 0x70, 0x61, 0x74, 0x68, 0x2f, 0x74, 0x6f, 0x2f, 0x6d, 0x79,
0x2f, 0x66, 0x69, 0x6c, 0x65, 0x2e, 0x74, 0x78, 0x74, 0xf2, 0x48, 0xcd,
0xc9, 0xc9, 0xd7, 0x51, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x4, 0x4, 0x0,
0x0, 0xff, 0xff, 0x50, 0x4b, 0x7, 0x8, 0xe6, 0xc6, 0xe6, 0xeb, 0x13, 0x0,
0x0, 0x0, 0xd, 0x0, 0x0, 0x0, 0x50, 0x4b, 0x1, 0x2, 0x14, 0x0, 0x14, 0x0,
0x8, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0xe6, 0xc6, 0xe6, 0xeb, 0x13, 0x0,
0x0, 0x0, 0xd, 0x0, 0x0, 0x0, 0x13, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x70, 0x61, 0x74, 0x68, 0x2f,
0x74, 0x6f, 0x2f, 0x6d, 0x79, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x2e, 0x74, 0x78,
0x74, 0x50, 0x4b, 0x5, 0x6, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x41,
0x0, 0x0, 0x0, 0x54, 0x0, 0x0, 0x0, 0x0, 0x0}
func openZipfile() *zip.Reader {
r, _ := zip.NewReader(bytes.NewReader(exampleFile), int64(len(exampleFile)))
return r
}
func ExampleList() {
zf := openZipfile()
List(zf, os.Stdout)
// Output: MODE SIZE NAME
// -rw-rw-rw- 13 path/to/my/file.txt
}
func ExampleFind() {
zf := openZipfile()
fmt.Println(Find(zf, "does", "not", "exist"))
fmt.Println(Find(zf, "path/to/my", "file.txt").Name)
// Output: <nil>
// path/to/my/file.txt
}
func ExampleOpen() {
zf := openZipfile()
source := stream.FromReadCloserError(Open(zf, "path/to/my/file.txt"))
stream.Copy(source, stream.ToWriter(os.Stdout))
// Output: Hello, world!
}
func ExampleExtract() {
tmp, err := ioutil.TempDir("", "ziptest")
if err != nil {
panic(err)
}
defer os.RemoveAll(tmp)
zf := openZipfile()
// extract all files/dirs under the path/to directory to tmp
if err := Extract(zf, "path/to", tmp); err != nil {
panic(err)
}
stream.Copy(stream.FromFile(tmp, "my", "file.txt"), stream.ToWriter(os.Stdout))
// Output: Hello, world!
}
func TestClean(t *testing.T) {
cases := map[string]struct {
Case []string
Expected string
}{
"blank": {
Case: []string{},
Expected: "",
},
"absolute": {
Case: []string{"/foo", "bar"},
Expected: "foo/bar",
},
"relative-dot": {
Case: []string{"./foo", "bar"},
Expected: "foo/bar",
},
"backslash": {
// This case will ONLY test validity on Windows based machines.
Case: []string{filepath.Join("windows", "system32")},
Expected: "windows/system32",
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := Clean(tc.Case...)
if actual != tc.Expected {
t.Errorf("expected: %q, actual: %q", tc.Expected, actual)
}
})
}
}
// This is a modified version of Golang's net/http/fs_test.go:TestServeFile_DotDot
func TestContainsDotDot(t *testing.T) {
tests := []struct {
req string
expected bool
}{
{"/testdata/file", false},
{"/../file", true},
{"/..", true},
{"/../", true},
{"/../foo", true},
{"/..\\foo", true},
{"/file/a", false},
{"/file/a..", false},
{"/file/a/..", true},
{"/file/a\\..", true},
}
for _, tt := range tests {
actual := containsDotDot(tt.req)
if actual != tt.expected {
t.Errorf("expected containsDotDot to be %t got %t", tt.expected, actual)
}
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/utils/ziputil/zip.go | utils/ziputil/zip.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 ziputil
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"text/tabwriter"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils/stream"
)
// List writes a ls -la style listing of the zipfile to the given writer.
func List(z *zip.Reader, w io.Writer) {
sw := tabwriter.NewWriter(w, 0, 0, 2, ' ', tabwriter.StripEscape)
fmt.Fprintln(sw, "MODE\tSIZE\tNAME")
for _, fd := range z.File {
fmt.Fprintf(sw, "%s\t%d\t%s\n", fd.Mode().String(), fd.UncompressedSize, fd.Name)
}
sw.Flush()
}
// Joins a path for use in a zip file.
func Join(path ...string) string {
return strings.Join(path, "/")
}
// Clean converts a path into a zip style path by replacing backslashes with
// forward-slashes and making the paths relative by removing leading "/" and "./".
func Clean(path ...string) string {
joined := filepath.ToSlash(Join(path...))
slashStrip := strings.TrimPrefix(joined, "/")
dotStrip := strings.TrimPrefix(slashStrip, "./")
return dotStrip
}
// Find returns a pointer to the file at the given path if it exists, otherwise
// nil.
func Find(z *zip.Reader, path ...string) *zip.File {
name := Join(path...)
for _, f := range z.File {
if f.Name == name {
return f
}
}
return nil
}
// Opens the file at the given path if possible, otherwise returns an error.
func Open(z *zip.Reader, path ...string) (io.ReadCloser, error) {
f := Find(z, path...)
if f == nil {
fmt.Errorf("no such file: %q", Join(path...))
}
return f.Open()
}
// Extracts the contents of the zipDirectory to the given OS osDirectory.
// This routine is overly strict and doesn't allow extracting _any_ files that
// contain "..".
func Extract(z *zip.Reader, zipDirectory, osDirectory string) error {
for _, fd := range z.File {
if fd.UncompressedSize == 0 { // skip directories
continue
}
if !strings.HasPrefix(fd.Name, zipDirectory) {
continue
}
if containsDotDot(fd.Name) {
return fmt.Errorf("potential zip slip extracting %q", fd.Name)
}
src := stream.FromReadCloserError(fd.Open())
newName := strings.TrimPrefix(fd.Name, zipDirectory)
destPath := filepath.Join(osDirectory, filepath.FromSlash(newName))
dest := stream.ToModeFile(fd.Mode(), destPath)
if err := stream.Copy(src, dest); err != nil {
return fmt.Errorf("couldn't extract file %q: %v", fd.Name, err)
}
}
return nil
}
// containsDotDot checks if the filepath value v contains a ".." entry.
// This will check filepath components by splitting along / or \. This
// function is copied directly from the Go net/http implementation.
func containsDotDot(v string) bool {
if !strings.Contains(v, "..") {
return false
}
for _, ent := range strings.FieldsFunc(v, isSlashRune) {
if ent == ".." {
return true
}
}
return false
}
func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
// Unarchive opens the specified file and extracts all of its contents to the
// destination.
func Unarchive(zipFile, destination string) error {
rdc, err := zip.OpenReader(zipFile)
if err != nil {
return fmt.Errorf("couldn't open archive %q: %v", zipFile, err)
}
defer rdc.Close()
return Extract(&rdc.Reader, "", destination)
}
// Archive creates a zip from the contents of the sourceFolder at the
// destinationZip location.
func Archive(sourceFolder, destinationZip string) error {
fd, err := os.Create(destinationZip)
if err != nil {
return fmt.Errorf("couldn't create archive %q: %v", destinationZip, err)
}
defer fd.Close()
w := zip.NewWriter(fd)
defer w.Close()
return filepath.Walk(sourceFolder, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = Clean(strings.TrimPrefix(path, sourceFolder))
header.Method = zip.Deflate
if info.IsDir() {
w.CreateHeader(header)
} else {
fd, err := w.CreateHeader(header)
if err != nil {
return err
}
if err := stream.Copy(stream.FromFile(path), stream.ToWriter(fd)); err != nil {
return err
}
}
return nil
})
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/migrations_test.go | db_service/migrations_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 db_service
import (
"errors"
"math"
"os"
"reflect"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/jinzhu/gorm"
)
func TestValidateLastMigration(t *testing.T) {
cases := map[string]struct {
LastMigration int
Expected error
}{
"new-db": {
LastMigration: -1,
Expected: nil,
},
"before-v2": {
LastMigration: 0,
Expected: errors.New("Migration from broker versions <= 2.0 is no longer supported, upgrade using a v3.x broker then try again."),
},
"v3-to-v4": {
LastMigration: 1,
Expected: nil,
},
"v4-to-v4.1": {
LastMigration: 2,
Expected: nil,
},
"v4.1-to-v4.2": {
LastMigration: 3,
Expected: nil,
},
"up-to-date": {
LastMigration: numMigrations - 1,
Expected: nil,
},
"future": {
LastMigration: numMigrations,
Expected: errors.New("The database you're connected to is newer than this tool supports."),
},
"far-future": {
LastMigration: math.MaxInt32,
Expected: errors.New("The database you're connected to is newer than this tool supports."),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := ValidateLastMigration(tc.LastMigration)
if !reflect.DeepEqual(actual, tc.Expected) {
t.Errorf("Expected error %v, got %v", tc.Expected, actual)
}
})
}
}
func TestRunMigrations_Failures(t *testing.T) {
cases := map[string]struct {
LastMigration int
Expected error
}{
"before-v2": {
LastMigration: 0,
Expected: errors.New("Migration from broker versions <= 2.0 is no longer supported, upgrade using a v3.x broker then try again."),
},
"future": {
LastMigration: numMigrations,
Expected: errors.New("The database you're connected to is newer than this tool supports."),
},
"far-future": {
LastMigration: math.MaxInt32,
Expected: errors.New("The database you're connected to is newer than this tool supports."),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
db, err := gorm.Open("sqlite3", "test.sqlite3")
defer os.Remove("test.sqlite3")
if err != nil {
t.Fatal(err)
}
if err := autoMigrateTables(db, &models.MigrationV1{}); err != nil {
t.Fatal(err)
}
if err := db.Save(&models.Migration{MigrationId: tc.LastMigration}).Error; err != nil {
t.Fatal(err)
}
actual := RunMigrations(db)
if !reflect.DeepEqual(actual, tc.Expected) {
t.Errorf("Expected error %v, got %v", tc.Expected, actual)
}
})
}
}
func TestRunMigrations(t *testing.T) {
cases := map[string]func(t *testing.T, db *gorm.DB){
"creates-migrations-table": func(t *testing.T, db *gorm.DB) {
if err := RunMigrations(db); err != nil {
t.Fatal(err)
}
if !db.HasTable("migrations") {
t.Error("Expected db to have migrations table")
}
},
"applies-all-migrations-when-run": func(t *testing.T, db *gorm.DB) {
if err := RunMigrations(db); err != nil {
t.Fatal(err)
}
var storedMigrations []models.Migration
if err := db.Order("id desc").Find(&storedMigrations).Error; err != nil {
t.Fatal(err)
}
lastMigrationNumber := storedMigrations[0].MigrationId
if lastMigrationNumber != numMigrations-1 {
t.Errorf("expected lastMigrationNumber to be %d, got %d", numMigrations-1, lastMigrationNumber)
}
},
"can-run-migrations-multiple-times": func(t *testing.T, db *gorm.DB) {
for i := 0; i < 10; i++ {
if err := RunMigrations(db); err != nil {
t.Fatal(err)
}
}
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
db, err := gorm.Open("sqlite3", "test.sqlite3")
defer os.Remove("test.sqlite3")
if err != nil {
t.Fatal(err)
}
tc(t, db)
})
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/migrations.go | db_service/migrations.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 db_service
import (
"errors"
"fmt"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/jinzhu/gorm"
)
const numMigrations = 7
// runs schema migrations on the provided service broker database to get it up to date
func RunMigrations(db *gorm.DB) error {
migrations := make([]func() error, numMigrations)
// initial migration - creates tables
migrations[0] = func() error { // v1.0
return autoMigrateTables(db,
&models.ServiceInstanceDetailsV1{},
&models.ServiceBindingCredentialsV1{},
&models.ProvisionRequestDetailsV1{},
&models.PlanDetailsV1{},
&models.MigrationV1{})
}
// adds CloudOperation table
migrations[1] = func() error { // v2.x
// NOTE: this migration used to have lots of custom logic, however it has
// been removed because brokers starting at v4 no longer support the
// functionality the migration required.
//
// It is acceptable to pass through this migration step on the way to
// intiailize a _new_ databse, but it is not acceptable to use this step
// in a path through the upgrade.
return autoMigrateTables(db, &models.CloudOperationV1{})
}
// drops plan details table
migrations[2] = func() error { // 4.0.0
// NOOP migration, this was used to drop the plan_details table, but
// there's more of a disincentive than incentive to do that because it could
// leave operators wiping out plain details accidentally and not being able
// to recover if they don't follow the upgrade path.
return nil
}
migrations[3] = func() error { // v4.1.0
return autoMigrateTables(db, &models.ServiceInstanceDetailsV2{})
}
migrations[4] = func() error { // v4.2.0
return autoMigrateTables(db, &models.TerraformDeploymentV1{})
}
migrations[5] = func() error { // v4.2.3
return autoMigrateTables(db, &models.ProvisionRequestDetailsV2{})
}
migrations[6] = func() error { // v4.2.4
if db.Dialect().GetName() == "sqlite3" {
// sqlite does not support changing column data types
return nil
} else {
return db.Model(&models.ProvisionRequestDetailsV2{}).ModifyColumn("request_details", "text").Error
}
}
var lastMigrationNumber = -1
// if we've run any migrations before, we should have a migrations table, so find the last one we ran
if db.HasTable("migrations") {
var storedMigrations []models.Migration
if err := db.Order("migration_id desc").Find(&storedMigrations).Error; err != nil {
return fmt.Errorf("Error getting last migration id even though migration table exists: %s", err)
}
lastMigrationNumber = storedMigrations[0].MigrationId
}
if err := ValidateLastMigration(lastMigrationNumber); err != nil {
return err
}
// starting from the last migration we ran + 1, run migrations until we are current
for i := lastMigrationNumber + 1; i < len(migrations); i++ {
tx := db.Begin()
err := migrations[i]()
if err != nil {
tx.Rollback()
return err
} else {
newMigration := models.Migration{
MigrationId: i,
}
if err := db.Save(&newMigration).Error; err != nil {
tx.Rollback()
return err
} else {
tx.Commit()
}
}
}
return nil
}
// ValidateLastMigration returns an error if the database version is newer than
// this tool supports or is too old to be updated.
func ValidateLastMigration(lastMigration int) error {
switch {
case lastMigration >= numMigrations:
return errors.New("The database you're connected to is newer than this tool supports.")
case lastMigration == 0:
return errors.New("Migration from broker versions <= 2.0 is no longer supported, upgrade using a v3.x broker then try again.")
default:
return nil
}
}
func autoMigrateTables(db *gorm.DB, tables ...interface{}) error {
if db.Dialect().GetName() == "mysql" {
return db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8").AutoMigrate(tables...).Error
} else {
return db.AutoMigrate(tables...).Error
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/dao_test.go | db_service/dao_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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.
// Code generated by go generate; DO NOT EDIT.
package db_service
import (
"context"
"testing"
"time"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/jinzhu/gorm"
)
func newInMemoryDatastore(t *testing.T) *SqlDatastore {
testDb, err := gorm.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("Error opening test database %s", err)
}
testDb.CreateTable(models.ServiceInstanceDetails{})
testDb.CreateTable(models.ServiceBindingCredentials{})
testDb.CreateTable(models.ProvisionRequestDetails{})
testDb.CreateTable(models.TerraformDeployment{})
return &SqlDatastore{db: testDb}
}
func createServiceInstanceDetailsInstance() (string, models.ServiceInstanceDetails) {
testPk := string(42)
instance := models.ServiceInstanceDetails{}
instance.ID = testPk
instance.Location = "loc"
instance.Name = "Hello"
instance.OrganizationGuid = "1111-1111-1111"
instance.OtherDetails = "{\"some\":[\"json\",\"blob\",\"here\"]}"
instance.PlanId = "planid"
instance.ServiceId = "123-456-7890"
instance.SpaceGuid = "0000-0000-0000"
instance.Url = "https://google.com"
return testPk, instance
}
func ensureServiceInstanceDetailsFieldsMatch(t *testing.T, expected, actual *models.ServiceInstanceDetails) {
if expected.Location != actual.Location {
t.Errorf("Expected field Location to be %#v, got %#v", expected.Location, actual.Location)
}
if expected.Name != actual.Name {
t.Errorf("Expected field Name to be %#v, got %#v", expected.Name, actual.Name)
}
if expected.OrganizationGuid != actual.OrganizationGuid {
t.Errorf("Expected field OrganizationGuid to be %#v, got %#v", expected.OrganizationGuid, actual.OrganizationGuid)
}
if expected.OtherDetails != actual.OtherDetails {
t.Errorf("Expected field OtherDetails to be %#v, got %#v", expected.OtherDetails, actual.OtherDetails)
}
if expected.PlanId != actual.PlanId {
t.Errorf("Expected field PlanId to be %#v, got %#v", expected.PlanId, actual.PlanId)
}
if expected.ServiceId != actual.ServiceId {
t.Errorf("Expected field ServiceId to be %#v, got %#v", expected.ServiceId, actual.ServiceId)
}
if expected.SpaceGuid != actual.SpaceGuid {
t.Errorf("Expected field SpaceGuid to be %#v, got %#v", expected.SpaceGuid, actual.SpaceGuid)
}
if expected.Url != actual.Url {
t.Errorf("Expected field Url to be %#v, got %#v", expected.Url, actual.Url)
}
}
func TestSqlDatastore_ServiceInstanceDetailsDAO(t *testing.T) {
ds := newInMemoryDatastore(t)
testPk, instance := createServiceInstanceDetailsInstance()
testCtx := context.Background()
// on startup, there should be no objects to find or delete
exists, err := ds.ExistsServiceInstanceDetailsById(testCtx, testPk)
ensureExistance(t, false, exists, err)
if _, err := ds.GetServiceInstanceDetailsById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing PK got %v", err)
}
// Should be able to create the item
beforeCreation := time.Now()
if err := ds.CreateServiceInstanceDetails(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetServiceInstanceDetailsById(testCtx, testPk)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureServiceInstanceDetailsFieldsMatch(t, &instance, ret)
// we should be able to update the item and it will have a new updated time
if err := ds.SaveServiceInstanceDetails(testCtx, ret); err != nil {
t.Errorf("Expected no error trying to get update %#v , got: %v", ret, err)
}
if !ret.UpdatedAt.After(ret.CreatedAt) {
t.Errorf("Expected update time to be after create time after update, got update: %#v create: %#v", ret.UpdatedAt, ret.CreatedAt)
}
// after deleting the item we should not be able to get it
if err := ds.DeleteServiceInstanceDetailsById(testCtx, testPk); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
if _, err := ds.GetServiceInstanceDetailsById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected ErrRecordNotFound after delete but got %v", err)
}
}
func TestSqlDatastore_GetServiceInstanceDetailsById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceInstanceDetailsInstance()
testCtx := context.Background()
if _, err := ds.GetServiceInstanceDetailsById(testCtx, instance.ID); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing record got %v", err)
}
beforeCreation := time.Now()
if err := ds.CreateServiceInstanceDetails(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetServiceInstanceDetailsById(testCtx, instance.ID)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureServiceInstanceDetailsFieldsMatch(t, &instance, ret)
}
func TestSqlDatastore_ExistsServiceInstanceDetailsById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceInstanceDetailsInstance()
testCtx := context.Background()
exists, err := ds.ExistsServiceInstanceDetailsById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
if err := ds.CreateServiceInstanceDetails(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
exists, err = ds.ExistsServiceInstanceDetailsById(testCtx, instance.ID)
ensureExistance(t, true, exists, err)
if err := ds.DeleteServiceInstanceDetails(testCtx, &instance); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
// we should be able to see that it was soft-deleted
exists, err = ds.ExistsServiceInstanceDetailsById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
}
func createServiceBindingCredentialsInstance() (uint, models.ServiceBindingCredentials) {
testPk := uint(42)
instance := models.ServiceBindingCredentials{}
instance.ID = testPk
instance.BindingId = "0000-0000-0000"
instance.OtherDetails = "{\"some\":[\"json\",\"blob\",\"here\"]}"
instance.ServiceId = "1111-1111-1111"
instance.ServiceInstanceId = "2222-2222-2222"
return testPk, instance
}
func ensureServiceBindingCredentialsFieldsMatch(t *testing.T, expected, actual *models.ServiceBindingCredentials) {
if expected.BindingId != actual.BindingId {
t.Errorf("Expected field BindingId to be %#v, got %#v", expected.BindingId, actual.BindingId)
}
if expected.OtherDetails != actual.OtherDetails {
t.Errorf("Expected field OtherDetails to be %#v, got %#v", expected.OtherDetails, actual.OtherDetails)
}
if expected.ServiceId != actual.ServiceId {
t.Errorf("Expected field ServiceId to be %#v, got %#v", expected.ServiceId, actual.ServiceId)
}
if expected.ServiceInstanceId != actual.ServiceInstanceId {
t.Errorf("Expected field ServiceInstanceId to be %#v, got %#v", expected.ServiceInstanceId, actual.ServiceInstanceId)
}
}
func TestSqlDatastore_ServiceBindingCredentialsDAO(t *testing.T) {
ds := newInMemoryDatastore(t)
testPk, instance := createServiceBindingCredentialsInstance()
testCtx := context.Background()
// on startup, there should be no objects to find or delete
exists, err := ds.ExistsServiceBindingCredentialsById(testCtx, testPk)
ensureExistance(t, false, exists, err)
if _, err := ds.GetServiceBindingCredentialsById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing PK got %v", err)
}
// Should be able to create the item
beforeCreation := time.Now()
if err := ds.CreateServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetServiceBindingCredentialsById(testCtx, testPk)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureServiceBindingCredentialsFieldsMatch(t, &instance, ret)
// we should be able to update the item and it will have a new updated time
if err := ds.SaveServiceBindingCredentials(testCtx, ret); err != nil {
t.Errorf("Expected no error trying to get update %#v , got: %v", ret, err)
}
if !ret.UpdatedAt.After(ret.CreatedAt) {
t.Errorf("Expected update time to be after create time after update, got update: %#v create: %#v", ret.UpdatedAt, ret.CreatedAt)
}
// after deleting the item we should not be able to get it
if err := ds.DeleteServiceBindingCredentialsById(testCtx, testPk); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
if _, err := ds.GetServiceBindingCredentialsById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected ErrRecordNotFound after delete but got %v", err)
}
}
func TestSqlDatastore_GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceBindingCredentialsInstance()
testCtx := context.Background()
if _, err := ds.GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(testCtx, instance.ServiceInstanceId, instance.BindingId); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing record got %v", err)
}
beforeCreation := time.Now()
if err := ds.CreateServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(testCtx, instance.ServiceInstanceId, instance.BindingId)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureServiceBindingCredentialsFieldsMatch(t, &instance, ret)
}
func TestSqlDatastore_ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceBindingCredentialsInstance()
testCtx := context.Background()
exists, err := ds.ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(testCtx, instance.ServiceInstanceId, instance.BindingId)
ensureExistance(t, false, exists, err)
if err := ds.CreateServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
exists, err = ds.ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(testCtx, instance.ServiceInstanceId, instance.BindingId)
ensureExistance(t, true, exists, err)
if err := ds.DeleteServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
// we should be able to see that it was soft-deleted
exists, err = ds.ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(testCtx, instance.ServiceInstanceId, instance.BindingId)
ensureExistance(t, false, exists, err)
}
func TestSqlDatastore_GetServiceBindingCredentialsByBindingId(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceBindingCredentialsInstance()
testCtx := context.Background()
if _, err := ds.GetServiceBindingCredentialsByBindingId(testCtx, instance.BindingId); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing record got %v", err)
}
beforeCreation := time.Now()
if err := ds.CreateServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetServiceBindingCredentialsByBindingId(testCtx, instance.BindingId)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureServiceBindingCredentialsFieldsMatch(t, &instance, ret)
}
func TestSqlDatastore_ExistsServiceBindingCredentialsByBindingId(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceBindingCredentialsInstance()
testCtx := context.Background()
exists, err := ds.ExistsServiceBindingCredentialsByBindingId(testCtx, instance.BindingId)
ensureExistance(t, false, exists, err)
if err := ds.CreateServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
exists, err = ds.ExistsServiceBindingCredentialsByBindingId(testCtx, instance.BindingId)
ensureExistance(t, true, exists, err)
if err := ds.DeleteServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
// we should be able to see that it was soft-deleted
exists, err = ds.ExistsServiceBindingCredentialsByBindingId(testCtx, instance.BindingId)
ensureExistance(t, false, exists, err)
}
func TestSqlDatastore_GetServiceBindingCredentialsById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceBindingCredentialsInstance()
testCtx := context.Background()
if _, err := ds.GetServiceBindingCredentialsById(testCtx, instance.ID); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing record got %v", err)
}
beforeCreation := time.Now()
if err := ds.CreateServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetServiceBindingCredentialsById(testCtx, instance.ID)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureServiceBindingCredentialsFieldsMatch(t, &instance, ret)
}
func TestSqlDatastore_ExistsServiceBindingCredentialsById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createServiceBindingCredentialsInstance()
testCtx := context.Background()
exists, err := ds.ExistsServiceBindingCredentialsById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
if err := ds.CreateServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
exists, err = ds.ExistsServiceBindingCredentialsById(testCtx, instance.ID)
ensureExistance(t, true, exists, err)
if err := ds.DeleteServiceBindingCredentials(testCtx, &instance); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
// we should be able to see that it was soft-deleted
exists, err = ds.ExistsServiceBindingCredentialsById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
}
func createProvisionRequestDetailsInstance() (uint, models.ProvisionRequestDetails) {
testPk := uint(42)
instance := models.ProvisionRequestDetails{}
instance.ID = testPk
instance.RequestDetails = "{\"some\":[\"json\",\"blob\",\"here\"]}"
instance.ServiceInstanceId = "2222-2222-2222"
return testPk, instance
}
func ensureProvisionRequestDetailsFieldsMatch(t *testing.T, expected, actual *models.ProvisionRequestDetails) {
if expected.RequestDetails != actual.RequestDetails {
t.Errorf("Expected field RequestDetails to be %#v, got %#v", expected.RequestDetails, actual.RequestDetails)
}
if expected.ServiceInstanceId != actual.ServiceInstanceId {
t.Errorf("Expected field ServiceInstanceId to be %#v, got %#v", expected.ServiceInstanceId, actual.ServiceInstanceId)
}
}
func TestSqlDatastore_ProvisionRequestDetailsDAO(t *testing.T) {
ds := newInMemoryDatastore(t)
testPk, instance := createProvisionRequestDetailsInstance()
testCtx := context.Background()
// on startup, there should be no objects to find or delete
exists, err := ds.ExistsProvisionRequestDetailsById(testCtx, testPk)
ensureExistance(t, false, exists, err)
if _, err := ds.GetProvisionRequestDetailsById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing PK got %v", err)
}
// Should be able to create the item
beforeCreation := time.Now()
if err := ds.CreateProvisionRequestDetails(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetProvisionRequestDetailsById(testCtx, testPk)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureProvisionRequestDetailsFieldsMatch(t, &instance, ret)
// we should be able to update the item and it will have a new updated time
if err := ds.SaveProvisionRequestDetails(testCtx, ret); err != nil {
t.Errorf("Expected no error trying to get update %#v , got: %v", ret, err)
}
if !ret.UpdatedAt.After(ret.CreatedAt) {
t.Errorf("Expected update time to be after create time after update, got update: %#v create: %#v", ret.UpdatedAt, ret.CreatedAt)
}
// after deleting the item we should not be able to get it
if err := ds.DeleteProvisionRequestDetailsById(testCtx, testPk); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
if _, err := ds.GetProvisionRequestDetailsById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected ErrRecordNotFound after delete but got %v", err)
}
}
func TestSqlDatastore_GetProvisionRequestDetailsById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createProvisionRequestDetailsInstance()
testCtx := context.Background()
if _, err := ds.GetProvisionRequestDetailsById(testCtx, instance.ID); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing record got %v", err)
}
beforeCreation := time.Now()
if err := ds.CreateProvisionRequestDetails(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetProvisionRequestDetailsById(testCtx, instance.ID)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureProvisionRequestDetailsFieldsMatch(t, &instance, ret)
}
func TestSqlDatastore_ExistsProvisionRequestDetailsById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createProvisionRequestDetailsInstance()
testCtx := context.Background()
exists, err := ds.ExistsProvisionRequestDetailsById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
if err := ds.CreateProvisionRequestDetails(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
exists, err = ds.ExistsProvisionRequestDetailsById(testCtx, instance.ID)
ensureExistance(t, true, exists, err)
if err := ds.DeleteProvisionRequestDetails(testCtx, &instance); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
// we should be able to see that it was soft-deleted
exists, err = ds.ExistsProvisionRequestDetailsById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
}
func createTerraformDeploymentInstance() (string, models.TerraformDeployment) {
testPk := string(42)
instance := models.TerraformDeployment{}
instance.ID = testPk
instance.LastOperationMessage = "Started 2018-01-01"
instance.LastOperationState = "in progress"
instance.LastOperationType = "create"
instance.Workspace = "{}"
return testPk, instance
}
func ensureTerraformDeploymentFieldsMatch(t *testing.T, expected, actual *models.TerraformDeployment) {
if expected.LastOperationMessage != actual.LastOperationMessage {
t.Errorf("Expected field LastOperationMessage to be %#v, got %#v", expected.LastOperationMessage, actual.LastOperationMessage)
}
if expected.LastOperationState != actual.LastOperationState {
t.Errorf("Expected field LastOperationState to be %#v, got %#v", expected.LastOperationState, actual.LastOperationState)
}
if expected.LastOperationType != actual.LastOperationType {
t.Errorf("Expected field LastOperationType to be %#v, got %#v", expected.LastOperationType, actual.LastOperationType)
}
if expected.Workspace != actual.Workspace {
t.Errorf("Expected field Workspace to be %#v, got %#v", expected.Workspace, actual.Workspace)
}
}
func TestSqlDatastore_TerraformDeploymentDAO(t *testing.T) {
ds := newInMemoryDatastore(t)
testPk, instance := createTerraformDeploymentInstance()
testCtx := context.Background()
// on startup, there should be no objects to find or delete
exists, err := ds.ExistsTerraformDeploymentById(testCtx, testPk)
ensureExistance(t, false, exists, err)
if _, err := ds.GetTerraformDeploymentById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing PK got %v", err)
}
// Should be able to create the item
beforeCreation := time.Now()
if err := ds.CreateTerraformDeployment(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetTerraformDeploymentById(testCtx, testPk)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureTerraformDeploymentFieldsMatch(t, &instance, ret)
// we should be able to update the item and it will have a new updated time
if err := ds.SaveTerraformDeployment(testCtx, ret); err != nil {
t.Errorf("Expected no error trying to get update %#v , got: %v", ret, err)
}
if !ret.UpdatedAt.After(ret.CreatedAt) {
t.Errorf("Expected update time to be after create time after update, got update: %#v create: %#v", ret.UpdatedAt, ret.CreatedAt)
}
// after deleting the item we should not be able to get it
if err := ds.DeleteTerraformDeploymentById(testCtx, testPk); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
if _, err := ds.GetTerraformDeploymentById(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected ErrRecordNotFound after delete but got %v", err)
}
}
func TestSqlDatastore_GetTerraformDeploymentById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createTerraformDeploymentInstance()
testCtx := context.Background()
if _, err := ds.GetTerraformDeploymentById(testCtx, instance.ID); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing record got %v", err)
}
beforeCreation := time.Now()
if err := ds.CreateTerraformDeployment(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.GetTerraformDeploymentById(testCtx, instance.ID)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensureTerraformDeploymentFieldsMatch(t, &instance, ret)
}
func TestSqlDatastore_ExistsTerraformDeploymentById(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := createTerraformDeploymentInstance()
testCtx := context.Background()
exists, err := ds.ExistsTerraformDeploymentById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
if err := ds.CreateTerraformDeployment(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
exists, err = ds.ExistsTerraformDeploymentById(testCtx, instance.ID)
ensureExistance(t, true, exists, err)
if err := ds.DeleteTerraformDeployment(testCtx, &instance); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
// we should be able to see that it was soft-deleted
exists, err = ds.ExistsTerraformDeploymentById(testCtx, instance.ID)
ensureExistance(t, false, exists, err)
}
func ensureExistance(t *testing.T, expected, actual bool, err error) {
if err != nil {
t.Fatalf("Expected err to be nil, got %v", err)
}
if expected != actual {
t.Fatalf("Expected exists to be %t got %t", expected, actual)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/vcap_test.go | db_service/vcap_test.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 db_service
import (
"fmt"
"os"
"testing"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
func ExampleUseVcapServices() {
os.Setenv("VCAP_SERVICES", `{
"p.mysql": [
{
"label": "p.mysql",
"name": "my-instance",
"plan": "db-medium",
"provider": null,
"syslog_drain_url": null,
"tags": [
"mysql"
],
"credentials": {
"hostname": "10.0.0.20",
"jdbcUrl": "jdbc:mysql://10.0.0.20:3306/service_instance_db?user=fefcbe8360854a18a7994b870e7b0bf5\u0026password=z9z6eskdbs1rhtxt",
"name": "service_instance_db",
"password": "z9z6eskdbs1rhtxt",
"port": 3306,
"uri": "mysql://fefcbe8360854a18a7994b870e7b0bf5:z9z6eskdbs1rhtxt@10.0.0.20:3306/service_instance_db?reconnect=true",
"username": "fefcbe8360854a18a7994b870e7b0bf5"
},
"volume_mounts": []
}
]
}`)
UseVcapServices()
fmt.Println(viper.Get(dbHostProp))
fmt.Println(viper.Get(dbUserProp))
fmt.Println(viper.Get(dbPassProp))
fmt.Println(viper.Get(dbNameProp))
// Output:
// 10.0.0.20
// fefcbe8360854a18a7994b870e7b0bf5
// z9z6eskdbs1rhtxt
// service_instance_db
}
func TestParseVcapServices(t *testing.T) {
cases := map[string]struct {
VcapServiceData string
ExpectedError error
}{
"empty vcap service": {
VcapServiceData: "",
ExpectedError: errors.New("Error unmarshalling VCAP_SERVICES: unexpected end of JSON input"),
},
"google-cloud vcap-service": {
VcapServiceData: `{
"google-cloudsql-mysql": [
{
"binding_name": "testbinding",
"instance_name": "testinstance",
"name": "kf-binding-tt2-mystorage",
"label": "google-storage",
"tags": [
"gcp",
"cloudsql",
"mysql"
],
"plan": "nearline",
"credentials": {
"CaCert": "-truncated-",
"ClientCert": "-truncated-",
"ClientKey": "-truncated-",
"Email": "pcf-binding-testbind@test-gsb.iam.gserviceaccount.com",
"Name": "pcf-binding-testbind",
"Password": "PASSWORD",
"PrivateKeyData": "PRIVATEKEY",
"ProjectId": "test-gsb",
"Sha1Fingerprint": "aa3bade266136f733642ebdb4992b89eb05f83c4",
"UniqueId": "108868434450972082663",
"UriPrefix": "",
"Username": "newuseraccount",
"database_name": "service_broker",
"host": "127.0.0.1",
"instance_name": "pcf-sb-1-1561406852899716453",
"last_master_operation_id": "",
"region": "",
"uri": "mysql://newuseraccount:PASSWORD@127.0.0.1/service_broker?ssl_mode=required"
}
}
]
}`,
ExpectedError: nil,
},
"pivotal vcap service": {
VcapServiceData: `{
"p.mysql": [
{
"label": "p.mysql",
"name": "my-instance",
"plan": "db-medium",
"provider": null,
"syslog_drain_url": null,
"tags": [
"mysql"
],
"credentials": {
"hostname": "10.0.0.20",
"jdbcUrl": "jdbc:mysql://10.0.0.20:3306/service_instance_db?user=fefcbe8360854a18a7994b870e7b0bf5\u0026password=z9z6eskdbs1rhtxt",
"name": "service_instance_db",
"password": "z9z6eskdbs1rhtxt",
"port": 3306,
"uri": "mysql://fefcbe8360854a18a7994b870e7b0bf5:z9z6eskdbs1rhtxt@10.0.0.20:3306/service_instance_db?reconnect=true",
"username": "fefcbe8360854a18a7994b870e7b0bf5"
},
"volume_mounts": []
}
]
}
`,
ExpectedError: nil,
},
"invalid vcap service - more than one mysql tag": {
VcapServiceData: `{
"google-cloudsql-mysql": [
{
"binding_name": "testbinding",
"instance_name": "testinstance",
"name": "kf-binding-tt2-mystorage",
"label": "google-storage",
"tags": [
"gcp",
"cloudsql",
"mysql"
],
"plan": "nearline",
"credentials": {
"CaCert": "-truncated-",
"ClientCert": "-truncated-",
"ClientKey": "-truncated-",
"Email": "pcf-binding-testbind@test-gsb.iam.gserviceaccount.com",
"Name": "pcf-binding-testbind",
"Password": "PASSWORD",
"PrivateKeyData": "PRIVATEKEY",
"ProjectId": "test-gsb",
"Sha1Fingerprint": "aa3bade266136f733642ebdb4992b89eb05f83c4",
"UniqueId": "108868434450972082663",
"UriPrefix": "",
"Username": "newuseraccount",
"database_name": "service_broker",
"host": "127.0.0.1",
"instance_name": "pcf-sb-1-1561406852899716453",
"last_master_operation_id": "",
"region": "",
"uri": "mysql://newuseraccount:PASSWORD@127.0.0.1/service_broker?ssl_mode=required"
}
},
{
"label": "p.mysql",
"name": "my-instance",
"plan": "db-medium",
"provider": null,
"syslog_drain_url": null,
"tags": [
"mysql"
],
"credentials": {
"hostname": "10.0.0.20",
"jdbcUrl": "jdbc:mysql://10.0.0.20:3306/service_instance_db?user=fefcbe8360854a18a7994b870e7b0bf5\u0026password=z9z6eskdbs1rhtxt",
"name": "service_instance_db",
"password": "z9z6eskdbs1rhtxt",
"port": 3306,
"uri": "mysql://fefcbe8360854a18a7994b870e7b0bf5:z9z6eskdbs1rhtxt@10.0.0.20:3306/service_instance_db?reconnect=true",
"username": "fefcbe8360854a18a7994b870e7b0bf5"
},
"volume_mounts": []
}
]
}`,
ExpectedError: errors.New("Error finding MySQL tag: The variable VCAP_SERVICES must have one VCAP service with a tag of 'mysql'. There are currently 2 VCAP services with the tag 'mysql'."),
},
"invalid vcap service - zero mysql tags": {
VcapServiceData: `{
"p.mysql": [
{
"label": "p.mysql",
"name": "my-instance",
"plan": "db-medium",
"provider": null,
"syslog_drain_url": null,
"tags": [
"notmysql"
],
"credentials": {
"hostname": "10.0.0.20",
"jdbcUrl": "jdbc:mysql://10.0.0.20:3306/service_instance_db?user=fefcbe8360854a18a7994b870e7b0bf5\u0026password=z9z6eskdbs1rhtxt",
"name": "service_instance_db",
"password": "z9z6eskdbs1rhtxt",
"port": 3306,
"uri": "mysql://fefcbe8360854a18a7994b870e7b0bf5:z9z6eskdbs1rhtxt@10.0.0.20:3306/service_instance_db?reconnect=true",
"username": "fefcbe8360854a18a7994b870e7b0bf5"
},
"volume_mounts": []
}
]
}
`,
ExpectedError: errors.New("Error finding MySQL tag: The variable VCAP_SERVICES must have one VCAP service with a tag of 'mysql'. There are currently 0 VCAP services with the tag 'mysql'."),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
vcapService, err := ParseVcapServices(tc.VcapServiceData)
if err == nil {
fmt.Printf("\n%#v\n", vcapService)
}
expectError(t, tc.ExpectedError, err)
})
}
}
func TestSetDatabaseCredentials(t *testing.T) {
cases := map[string]struct {
VcapService VcapService
ExpectedError error
}{
"empty vcap service": {
VcapService: VcapService{},
ExpectedError: nil,
},
"valid gcp vcap service": {
VcapService: VcapService{
BindingName: "testbinding",
InstanceName: "testinstance",
Name: "kf-binding-tt2-mystorage",
Label: "google-storage",
Tags: []string{"gcp", "cloudsql", "mysql"},
Plan: "nearline",
Credentials: map[string]interface{}{
"CaCert": "-truncated-",
"ClientCert": "-truncated-",
"ClientKey": "-truncated-",
"Email": "pcf-binding-testbind@test-gsb.iam.gserviceaccount.com",
"Name": "pcf-binding-testbind",
"Password": "Ukd7QEmrfC7xMRqNmTzHCbNnmBtNceys1olOzLoSm4k",
"PrivateKeyData": "-truncated-",
"ProjectId": "test-gsb",
"Sha1Fingerprint": "aa3bade266136f733642ebdb4992b89eb05f83c4",
"UniqueId": "108868434450972082663",
"UriPrefix": "",
"Username": "newuseraccount",
"database_name": "service_broker",
"host": "104.154.90.3",
"instance_name": "pcf-sb-1-1561406852899716453",
"last_master_operation_id": "",
"region": "",
"uri": "mysql://newuseraccount:Ukd7QEmrfC7xMRqNmTzHCbNnmBtNceys1olOzLoSm4k@104.154.90.3/service_broker?ssl_mode=required",
},
},
ExpectedError: nil,
},
"valid pivotal vcap service": {
VcapService: VcapService{
BindingName: "",
InstanceName: "",
Name: "my-instance",
Label: "p.mysql",
Tags: []string{"mysql"},
Plan: "db-medium",
Credentials: map[string]interface{}{
"hostname": "10.0.0.20",
"jdbcUrl": "jdbc:mysql://10.0.0.20:3306/service_instance_db?user=fefcbe8360854a18a7994b870e7b0bf5&password=z9z6eskdbs1rhtxt",
"name": "service_instance_db",
"password": "z9z6eskdbs1rhtxt",
"port": 3306,
"uri": "mysql://fefcbe8360854a18a7994b870e7b0bf5:z9z6eskdbs1rhtxt@10.0.0.20:3306/service_instance_db?reconnect=true",
"username": "fefcbe8360854a18a7994b870e7b0bf5",
},
},
ExpectedError: nil,
},
"invalid vcap service - malformed uri": {
VcapService: VcapService{
BindingName: "",
InstanceName: "",
Name: "my-instance",
Label: "p.mysql",
Tags: []string{"mysql"},
Plan: "db-medium",
Credentials: map[string]interface{}{
"hostname": "10.0.0.20",
"jdbcUrl": "jdbc:mysql://10.0.0.20:3306/service_instance_db?user=fefcbe8360854a18a7994b870e7b0bf5&password=z9z6eskdbs1rhtxt",
"name": "service_instance_db",
"password": "z9z6eskdbs1rhtxt",
"port": 3306,
"uri": "mys@!ql://fefcbe8360854a18a7994b870e7b0bf5:z9z6eskdbs1rhtxt@10.0.0.20:3306/service_instance_db?reconnect=true",
"username": "fefcbe8360854a18a7994b870e7b0bf5",
},
},
ExpectedError: errors.New("Error parsing credentials uri field: parse \"mys@!ql://fefcbe8360854a18a7994b870e7b0bf5:z9z6eskdbs1rhtxt@10.0.0.20:3306/service_instance_db?reconnect=true\": first path segment in URL cannot contain colon"),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
err := SetDatabaseCredentials(tc.VcapService)
expectError(t, tc.ExpectedError, err)
})
}
}
func expectError(t *testing.T, expected, actual error) {
t.Helper()
expectedErr := expected != nil
gotErr := actual != nil
switch {
case expectedErr && gotErr:
if expected.Error() != actual.Error() {
t.Fatalf("Expected: %v, got: %v", expected, actual)
}
case expectedErr && !gotErr:
t.Fatalf("Expected: %v, got: %v", expected, actual)
case !expectedErr && gotErr:
t.Fatalf("Expected no error but got: %v", actual)
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/setup_db.go | db_service/setup_db.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 db_service
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"code.cloudfoundry.org/lager"
"github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/spf13/viper"
)
const (
caCertProp = "db.ca.cert"
clientCertProp = "db.client.cert"
clientKeyProp = "db.client.key"
dbHostProp = "db.host"
dbUserProp = "db.user"
dbPassProp = "db.password"
dbPortProp = "db.port"
dbNameProp = "db.name"
dbTypeProp = "db.type"
dbPathProp = "db.path"
DbTypeMysql = "mysql"
DbTypeSqlite3 = "sqlite3"
)
func init() {
viper.BindEnv(caCertProp, "CA_CERT")
viper.BindEnv(clientCertProp, "CLIENT_CERT")
viper.BindEnv(clientKeyProp, "CLIENT_KEY")
viper.BindEnv(dbHostProp, "DB_HOST")
viper.BindEnv(dbUserProp, "DB_USERNAME")
viper.BindEnv(dbPassProp, "DB_PASSWORD")
viper.BindEnv(dbPortProp, "DB_PORT")
viper.SetDefault(dbPortProp, "3306")
viper.BindEnv(dbNameProp, "DB_NAME")
viper.SetDefault(dbNameProp, "servicebroker")
viper.BindEnv(dbTypeProp, "DB_TYPE")
viper.SetDefault(dbTypeProp, DbTypeMysql)
viper.BindEnv(dbPathProp, "DB_PATH")
}
// pulls db credentials from the environment, connects to the db, and returns the db connection
func SetupDb(logger lager.Logger) *gorm.DB {
dbType := viper.GetString(dbTypeProp)
var db *gorm.DB
var err error
// if provided, use database injected by CF via VCAP_SERVICES environment variable
if err := UseVcapServices(); err != nil {
logger.Error("Invalid VCAP_SERVICES environment variable", err)
os.Exit(1)
}
switch dbType {
default:
logger.Error("Database Setup", fmt.Errorf("Invalid database type %q, valid types are: sqlite3 and mysql", dbType))
os.Exit(1)
case DbTypeMysql:
db, err = setupMysqlDb(logger)
case DbTypeSqlite3:
db, err = setupSqlite3Db(logger)
}
if err != nil {
logger.Error("Database Setup", err)
os.Exit(1)
}
return db
}
func setupSqlite3Db(logger lager.Logger) (*gorm.DB, error) {
dbPath := viper.GetString(dbPathProp)
if dbPath == "" {
return nil, fmt.Errorf("You must set a database path when using SQLite3 databases")
}
logger.Info("WARNING: DO NOT USE SQLITE3 IN PRODUCTION!")
return gorm.Open(DbTypeSqlite3, dbPath)
}
func setupMysqlDb(logger lager.Logger) (*gorm.DB, error) {
// connect to database
dbHost := viper.GetString(dbHostProp)
dbUsername := viper.GetString(dbUserProp)
dbPassword := viper.GetString(dbPassProp)
if dbPassword == "" || dbHost == "" || dbUsername == "" {
return nil, errors.New("DB_HOST, DB_USERNAME and DB_PASSWORD are required environment variables.")
}
dbPort := viper.GetString(dbPortProp)
dbName := viper.GetString(dbNameProp)
tlsStr, err := generateTlsStringFromEnv()
if err != nil {
return nil, fmt.Errorf("Error generating TLS string from env: %s", err)
}
logger.Info("Connecting to MySQL Database", lager.Data{
"host": dbHost,
"port": dbPort,
"name": dbName,
})
connStr := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8&parseTime=True&loc=Local%v", dbUsername, dbPassword, dbHost, dbPort, dbName, tlsStr)
return gorm.Open(DbTypeMysql, connStr)
}
func generateTlsStringFromEnv() (string, error) {
caCert := viper.GetString(caCertProp)
clientCertStr := viper.GetString(clientCertProp)
clientKeyStr := viper.GetString(clientKeyProp)
tlsStr := "&tls=custom"
// make sure ssl is set up for this connection
if caCert != "" && clientCertStr != "" && clientKeyStr != "" {
rootCertPool := x509.NewCertPool()
if ok := rootCertPool.AppendCertsFromPEM([]byte(caCert)); !ok {
return "", fmt.Errorf("Error appending cert: %s", errors.New(""))
}
clientCert := make([]tls.Certificate, 0, 1)
certs, err := tls.X509KeyPair([]byte(clientCertStr), []byte(clientKeyStr))
if err != nil {
return "", fmt.Errorf("Error parsing cert pair: %s", err)
}
clientCert = append(clientCert, certs)
mysql.RegisterTLSConfig("custom", &tls.Config{
RootCAs: rootCertPool,
Certificates: clientCert,
InsecureSkipVerify: true,
})
} else {
tlsStr = ""
}
return tlsStr, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/dao.go | db_service/dao.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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.
// Code generated by go generate; DO NOT EDIT.
package db_service
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/jinzhu/gorm"
)
// CreateServiceInstanceDetails creates a new record in the database and assigns it a primary key.
func CreateServiceInstanceDetails(ctx context.Context, object *models.ServiceInstanceDetails) error { return defaultDatastore().CreateServiceInstanceDetails(ctx, object) }
func (ds *SqlDatastore) CreateServiceInstanceDetails(ctx context.Context, object *models.ServiceInstanceDetails) error {
return ds.db.Create(object).Error
}
// SaveServiceInstanceDetails updates an existing record in the database.
func SaveServiceInstanceDetails(ctx context.Context, object *models.ServiceInstanceDetails) error { return defaultDatastore().SaveServiceInstanceDetails(ctx, object) }
func (ds *SqlDatastore) SaveServiceInstanceDetails(ctx context.Context, object *models.ServiceInstanceDetails) error {
return ds.db.Save(object).Error
}
// DeleteServiceInstanceDetailsById soft-deletes the record by its key (id).
func DeleteServiceInstanceDetailsById(ctx context.Context, id string) error { return defaultDatastore().DeleteServiceInstanceDetailsById(ctx, id) }
func (ds *SqlDatastore) DeleteServiceInstanceDetailsById(ctx context.Context, id string) error {
return ds.db.Where("id = ?", id).Delete(&models.ServiceInstanceDetails{}).Error
}
// DeleteServiceInstanceDetails soft-deletes the record.
func DeleteServiceInstanceDetails(ctx context.Context, record *models.ServiceInstanceDetails) error { return defaultDatastore().DeleteServiceInstanceDetails(ctx, record) }
func (ds *SqlDatastore) DeleteServiceInstanceDetails(ctx context.Context, record *models.ServiceInstanceDetails) error {
return ds.db.Delete(record).Error
}
// GetServiceInstanceDetailsById gets an instance of ServiceInstanceDetails by its key (id).
func GetServiceInstanceDetailsById(ctx context.Context, id string) (*models.ServiceInstanceDetails, error) { return defaultDatastore().GetServiceInstanceDetailsById(ctx, id) }
func (ds *SqlDatastore) GetServiceInstanceDetailsById(ctx context.Context, id string) (*models.ServiceInstanceDetails, error) {
record := models.ServiceInstanceDetails{}
if err := ds.db.Where("id = ?", id).First(&record).Error; err != nil {
return nil, err
}
return &record, nil
}
// ExistsServiceInstanceDetailsById checks to see if an instance of ServiceInstanceDetails exists by its key (id).
func ExistsServiceInstanceDetailsById(ctx context.Context, id string) (bool, error) { return defaultDatastore().ExistsServiceInstanceDetailsById(ctx, id) }
func (ds *SqlDatastore) ExistsServiceInstanceDetailsById(ctx context.Context, id string) (bool, error) {
return recordToExists(ds.GetServiceInstanceDetailsById(ctx, id))
}
// CreateServiceBindingCredentials creates a new record in the database and assigns it a primary key.
func CreateServiceBindingCredentials(ctx context.Context, object *models.ServiceBindingCredentials) error { return defaultDatastore().CreateServiceBindingCredentials(ctx, object) }
func (ds *SqlDatastore) CreateServiceBindingCredentials(ctx context.Context, object *models.ServiceBindingCredentials) error {
return ds.db.Create(object).Error
}
// SaveServiceBindingCredentials updates an existing record in the database.
func SaveServiceBindingCredentials(ctx context.Context, object *models.ServiceBindingCredentials) error { return defaultDatastore().SaveServiceBindingCredentials(ctx, object) }
func (ds *SqlDatastore) SaveServiceBindingCredentials(ctx context.Context, object *models.ServiceBindingCredentials) error {
return ds.db.Save(object).Error
}
// DeleteServiceBindingCredentialsByServiceInstanceIdAndBindingId soft-deletes the record by its key (serviceInstanceId, bindingId).
func DeleteServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx context.Context, serviceInstanceId string, bindingId string) error { return defaultDatastore().DeleteServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx, serviceInstanceId, bindingId) }
func (ds *SqlDatastore) DeleteServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx context.Context, serviceInstanceId string, bindingId string) error {
return ds.db.Where("service_instance_id = ? AND binding_id = ?", serviceInstanceId, bindingId).Delete(&models.ServiceBindingCredentials{}).Error
}
// DeleteServiceBindingCredentialsByBindingId soft-deletes the record by its key (bindingId).
func DeleteServiceBindingCredentialsByBindingId(ctx context.Context, bindingId string) error { return defaultDatastore().DeleteServiceBindingCredentialsByBindingId(ctx, bindingId) }
func (ds *SqlDatastore) DeleteServiceBindingCredentialsByBindingId(ctx context.Context, bindingId string) error {
return ds.db.Where("binding_id = ?", bindingId).Delete(&models.ServiceBindingCredentials{}).Error
}
// DeleteServiceBindingCredentialsById soft-deletes the record by its key (id).
func DeleteServiceBindingCredentialsById(ctx context.Context, id uint) error { return defaultDatastore().DeleteServiceBindingCredentialsById(ctx, id) }
func (ds *SqlDatastore) DeleteServiceBindingCredentialsById(ctx context.Context, id uint) error {
return ds.db.Where("id = ?", id).Delete(&models.ServiceBindingCredentials{}).Error
}
// DeleteServiceBindingCredentials soft-deletes the record.
func DeleteServiceBindingCredentials(ctx context.Context, record *models.ServiceBindingCredentials) error { return defaultDatastore().DeleteServiceBindingCredentials(ctx, record) }
func (ds *SqlDatastore) DeleteServiceBindingCredentials(ctx context.Context, record *models.ServiceBindingCredentials) error {
return ds.db.Delete(record).Error
}
// GetServiceBindingCredentialsByServiceInstanceIdAndBindingId gets an instance of ServiceBindingCredentials by its key (serviceInstanceId, bindingId).
func GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx context.Context, serviceInstanceId string, bindingId string) (*models.ServiceBindingCredentials, error) { return defaultDatastore().GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx, serviceInstanceId, bindingId) }
func (ds *SqlDatastore) GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx context.Context, serviceInstanceId string, bindingId string) (*models.ServiceBindingCredentials, error) {
record := models.ServiceBindingCredentials{}
if err := ds.db.Where("service_instance_id = ? AND binding_id = ?", serviceInstanceId, bindingId).First(&record).Error; err != nil {
return nil, err
}
return &record, nil
}
// ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId checks to see if an instance of ServiceBindingCredentials exists by its key (serviceInstanceId, bindingId).
func ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx context.Context, serviceInstanceId string, bindingId string) (bool, error) { return defaultDatastore().ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx, serviceInstanceId, bindingId) }
func (ds *SqlDatastore) ExistsServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx context.Context, serviceInstanceId string, bindingId string) (bool, error) {
return recordToExists(ds.GetServiceBindingCredentialsByServiceInstanceIdAndBindingId(ctx, serviceInstanceId, bindingId))
}
// GetServiceBindingCredentialsByBindingId gets an instance of ServiceBindingCredentials by its key (bindingId).
func GetServiceBindingCredentialsByBindingId(ctx context.Context, bindingId string) (*models.ServiceBindingCredentials, error) { return defaultDatastore().GetServiceBindingCredentialsByBindingId(ctx, bindingId) }
func (ds *SqlDatastore) GetServiceBindingCredentialsByBindingId(ctx context.Context, bindingId string) (*models.ServiceBindingCredentials, error) {
record := models.ServiceBindingCredentials{}
if err := ds.db.Where("binding_id = ?", bindingId).First(&record).Error; err != nil {
return nil, err
}
return &record, nil
}
// ExistsServiceBindingCredentialsByBindingId checks to see if an instance of ServiceBindingCredentials exists by its key (bindingId).
func ExistsServiceBindingCredentialsByBindingId(ctx context.Context, bindingId string) (bool, error) { return defaultDatastore().ExistsServiceBindingCredentialsByBindingId(ctx, bindingId) }
func (ds *SqlDatastore) ExistsServiceBindingCredentialsByBindingId(ctx context.Context, bindingId string) (bool, error) {
return recordToExists(ds.GetServiceBindingCredentialsByBindingId(ctx, bindingId))
}
// GetServiceBindingCredentialsById gets an instance of ServiceBindingCredentials by its key (id).
func GetServiceBindingCredentialsById(ctx context.Context, id uint) (*models.ServiceBindingCredentials, error) { return defaultDatastore().GetServiceBindingCredentialsById(ctx, id) }
func (ds *SqlDatastore) GetServiceBindingCredentialsById(ctx context.Context, id uint) (*models.ServiceBindingCredentials, error) {
record := models.ServiceBindingCredentials{}
if err := ds.db.Where("id = ?", id).First(&record).Error; err != nil {
return nil, err
}
return &record, nil
}
// ExistsServiceBindingCredentialsById checks to see if an instance of ServiceBindingCredentials exists by its key (id).
func ExistsServiceBindingCredentialsById(ctx context.Context, id uint) (bool, error) { return defaultDatastore().ExistsServiceBindingCredentialsById(ctx, id) }
func (ds *SqlDatastore) ExistsServiceBindingCredentialsById(ctx context.Context, id uint) (bool, error) {
return recordToExists(ds.GetServiceBindingCredentialsById(ctx, id))
}
// CreateProvisionRequestDetails creates a new record in the database and assigns it a primary key.
func CreateProvisionRequestDetails(ctx context.Context, object *models.ProvisionRequestDetails) error { return defaultDatastore().CreateProvisionRequestDetails(ctx, object) }
func (ds *SqlDatastore) CreateProvisionRequestDetails(ctx context.Context, object *models.ProvisionRequestDetails) error {
return ds.db.Create(object).Error
}
// SaveProvisionRequestDetails updates an existing record in the database.
func SaveProvisionRequestDetails(ctx context.Context, object *models.ProvisionRequestDetails) error { return defaultDatastore().SaveProvisionRequestDetails(ctx, object) }
func (ds *SqlDatastore) SaveProvisionRequestDetails(ctx context.Context, object *models.ProvisionRequestDetails) error {
return ds.db.Save(object).Error
}
// DeleteProvisionRequestDetailsById soft-deletes the record by its key (id).
func DeleteProvisionRequestDetailsById(ctx context.Context, id uint) error { return defaultDatastore().DeleteProvisionRequestDetailsById(ctx, id) }
func (ds *SqlDatastore) DeleteProvisionRequestDetailsById(ctx context.Context, id uint) error {
return ds.db.Where("id = ?", id).Delete(&models.ProvisionRequestDetails{}).Error
}
// DeleteProvisionRequestDetails soft-deletes the record.
func DeleteProvisionRequestDetails(ctx context.Context, record *models.ProvisionRequestDetails) error { return defaultDatastore().DeleteProvisionRequestDetails(ctx, record) }
func (ds *SqlDatastore) DeleteProvisionRequestDetails(ctx context.Context, record *models.ProvisionRequestDetails) error {
return ds.db.Delete(record).Error
}
// GetProvisionRequestDetailsById gets an instance of ProvisionRequestDetails by its key (id).
func GetProvisionRequestDetailsById(ctx context.Context, id uint) (*models.ProvisionRequestDetails, error) { return defaultDatastore().GetProvisionRequestDetailsById(ctx, id) }
func (ds *SqlDatastore) GetProvisionRequestDetailsById(ctx context.Context, id uint) (*models.ProvisionRequestDetails, error) {
record := models.ProvisionRequestDetails{}
if err := ds.db.Where("id = ?", id).First(&record).Error; err != nil {
return nil, err
}
return &record, nil
}
// ExistsProvisionRequestDetailsById checks to see if an instance of ProvisionRequestDetails exists by its key (id).
func ExistsProvisionRequestDetailsById(ctx context.Context, id uint) (bool, error) { return defaultDatastore().ExistsProvisionRequestDetailsById(ctx, id) }
func (ds *SqlDatastore) ExistsProvisionRequestDetailsById(ctx context.Context, id uint) (bool, error) {
return recordToExists(ds.GetProvisionRequestDetailsById(ctx, id))
}
// CreateTerraformDeployment creates a new record in the database and assigns it a primary key.
func CreateTerraformDeployment(ctx context.Context, object *models.TerraformDeployment) error { return defaultDatastore().CreateTerraformDeployment(ctx, object) }
func (ds *SqlDatastore) CreateTerraformDeployment(ctx context.Context, object *models.TerraformDeployment) error {
return ds.db.Create(object).Error
}
// SaveTerraformDeployment updates an existing record in the database.
func SaveTerraformDeployment(ctx context.Context, object *models.TerraformDeployment) error { return defaultDatastore().SaveTerraformDeployment(ctx, object) }
func (ds *SqlDatastore) SaveTerraformDeployment(ctx context.Context, object *models.TerraformDeployment) error {
return ds.db.Save(object).Error
}
// DeleteTerraformDeploymentById soft-deletes the record by its key (id).
func DeleteTerraformDeploymentById(ctx context.Context, id string) error { return defaultDatastore().DeleteTerraformDeploymentById(ctx, id) }
func (ds *SqlDatastore) DeleteTerraformDeploymentById(ctx context.Context, id string) error {
return ds.db.Where("id = ?", id).Delete(&models.TerraformDeployment{}).Error
}
// DeleteTerraformDeployment soft-deletes the record.
func DeleteTerraformDeployment(ctx context.Context, record *models.TerraformDeployment) error { return defaultDatastore().DeleteTerraformDeployment(ctx, record) }
func (ds *SqlDatastore) DeleteTerraformDeployment(ctx context.Context, record *models.TerraformDeployment) error {
return ds.db.Delete(record).Error
}
// GetTerraformDeploymentById gets an instance of TerraformDeployment by its key (id).
func GetTerraformDeploymentById(ctx context.Context, id string) (*models.TerraformDeployment, error) { return defaultDatastore().GetTerraformDeploymentById(ctx, id) }
func (ds *SqlDatastore) GetTerraformDeploymentById(ctx context.Context, id string) (*models.TerraformDeployment, error) {
record := models.TerraformDeployment{}
if err := ds.db.Where("id = ?", id).First(&record).Error; err != nil {
return nil, err
}
return &record, nil
}
// ExistsTerraformDeploymentById checks to see if an instance of TerraformDeployment exists by its key (id).
func ExistsTerraformDeploymentById(ctx context.Context, id string) (bool, error) { return defaultDatastore().ExistsTerraformDeploymentById(ctx, id) }
func (ds *SqlDatastore) ExistsTerraformDeploymentById(ctx context.Context, id string) (bool, error) {
return recordToExists(ds.GetTerraformDeploymentById(ctx, id))
}
func recordToExists(_ interface{}, err error) (bool, error) {
if err != nil {
if gorm.IsRecordNotFoundError(err) {
return false, nil
}
return false, err
}
return true, nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/dao_generator.go | db_service/dao_generator.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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.
// +build ignore
// This program generates dao.go It can be invoked by running
// go generate
package main
import (
"fmt"
"log"
"os"
"strings"
"text/template"
"time"
)
func main() {
models := []crudModel{
{
Type: "ServiceInstanceDetails",
PrimaryKeyType: "string",
PrimaryKeyField: "id",
ExampleFields: map[string]interface{}{
"Name": "Hello",
"Location": "loc",
"Url": "https://google.com",
"OtherDetails": `{"some":["json","blob","here"]}`,
"ServiceId": "123-456-7890",
"PlanId": "planid",
"SpaceGuid": "0000-0000-0000",
"OrganizationGuid": "1111-1111-1111",
},
},
{
Type: "ServiceBindingCredentials",
PrimaryKeyType: "uint",
PrimaryKeyField: "id",
Keys: []fieldList{
{
{Type: "string", Column: "service_instance_id"},
{Type: "string", Column: "binding_id"},
},
{
{Type: "string", Column: "binding_id"},
},
},
ExampleFields: map[string]interface{}{
"ServiceId": "1111-1111-1111",
"ServiceInstanceId": "2222-2222-2222",
"BindingId": "0000-0000-0000",
"OtherDetails": `{"some":["json","blob","here"]}`,
},
},
{
Type: "ProvisionRequestDetails",
PrimaryKeyType: "uint",
PrimaryKeyField: "id",
ExampleFields: map[string]interface{}{
"ServiceInstanceId": "2222-2222-2222",
"RequestDetails": `{"some":["json","blob","here"]}`,
},
},
{
Type: "TerraformDeployment",
PrimaryKeyType: "string",
PrimaryKeyField: "id",
Keys: []fieldList{},
ExampleFields: map[string]interface{}{
"Workspace": "{}",
"LastOperationType": "create",
"LastOperationState": `in progress`,
"LastOperationMessage": `Started 2018-01-01`,
},
},
}
for i, model := range models {
pk := fieldList{{Type: model.PrimaryKeyType, Column: model.PrimaryKeyField}}
models[i].Keys = append(model.Keys, pk)
}
createDao(models)
createDaoTest(models)
}
func createDao(models []crudModel) {
f, err := os.Create("dao.go")
die(err)
defer f.Close()
daoTemplate.Execute(f, struct {
Timestamp time.Time
Models []crudModel
}{
Timestamp: time.Now(),
Models: models,
})
}
func createDaoTest(models []crudModel) {
f, err := os.Create("dao_test.go")
die(err)
defer f.Close()
daoTestTemplate.Execute(f, struct {
Timestamp time.Time
Models []crudModel
}{
Timestamp: time.Now(),
Models: models,
})
}
func die(err error) {
if err != nil {
log.Fatal(err)
}
}
type crudModel struct {
Type string
PrimaryKeyType string
PrimaryKeyField string
ExampleFields map[string]interface{}
Keys []fieldList
}
type fieldList []crudField
// WhereClause generates a gorm Where clause function and arguments.
func (fl fieldList) WhereClause() string {
var cols []string
for _, field := range fl {
cols = append(cols, field.Column+" = ?")
}
colf := strings.Join(cols, " AND ")
return fmt.Sprintf("Where(%q, %s)", colf, fl.CallParams())
}
// FuncName gets the concatenated function argument descriptor in a
// Spring Data Repository style i.e. <Verb>By(<Field>And)*(<Field>).
func (fl fieldList) FuncName() string {
out := ""
for i, field := range fl {
if i == 0 {
out += "By"
} else {
out += "And"
}
out += snakeToProper(field.Column)
}
return out
}
// Args creates field type argument pairs to use when defining function params.
func (fl fieldList) Args() string {
var args []string
for _, field := range fl {
arg := fmt.Sprintf("%s %s", snakeToCamel(field.Column), field.Type)
args = append(args, arg)
}
return strings.Join(args, ", ")
}
// CallParams gets the camelCase of the columns in the field list joined by commas
// like you'd need for calling the function generated by Args().
func (fl fieldList) CallParams() string {
var args []string
for _, field := range fl {
args = append(args, snakeToCamel(field.Column))
}
return strings.Join(args, ", ")
}
// ExampleArgs is like CallParams, but with the properties on the struct parent.
// e.g. ExampleArgs(foo) would return "foo.ID, foo.PropertyA, foo.PropertyB"
func (fl fieldList) ExampleArgs(parent string) string {
var exampleArgs []string
for _, field := range fl {
fieldName := snakeToProper(field.Column)
if fieldName == "Id" {
fieldName = "ID"
}
exampleArgs = append(exampleArgs, parent+"."+fieldName)
}
return strings.Join(exampleArgs, ", ")
}
type crudField struct {
Type string
Column string
}
func snakeToCamel(in string) string {
proper := snakeToProper(in)
return strings.ToLower(proper[0:1]) + proper[1:]
}
func snakeToProper(in string) string {
out := ""
for _, word := range strings.Split(in, "_") {
if len(word) == 0 {
continue
}
out += strings.ToUpper(word[0:1]) + strings.ToLower(word[1:])
}
return out
}
func functionNameGen(operation string, objType string, keys ...string) string {
out := operation + objType
for i, key := range keys {
if i == 0 {
out += "By"
} else {
out += "And"
}
out += snakeToProper(key)
}
return out
}
var daoTemplate = template.Must(template.New("").Funcs(
template.FuncMap{
"funcName": functionNameGen,
},
).Parse(`// Copyright {{ .Timestamp.Year }} the Service Broker Project Authors.
//
// 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.
// Code generated by go generate; DO NOT EDIT.
package db_service
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/jinzhu/gorm"
)
{{- range .Models}}
{{- $type := .Type}}
// {{funcName "Create" .Type}} creates a new record in the database and assigns it a primary key.
func {{funcName "Create" .Type}}(ctx context.Context, object *models.{{.Type}}) error { return defaultDatastore().{{funcName "Create" .Type}}(ctx, object) }
func (ds *SqlDatastore) Create{{.Type}}(ctx context.Context, object *models.{{.Type}}) error {
return ds.db.Create(object).Error
}
// {{funcName "Save" .Type}} updates an existing record in the database.
func {{funcName "Save" .Type}}(ctx context.Context, object *models.{{.Type}}) error { return defaultDatastore().{{funcName "Save" .Type}}(ctx, object) }
func (ds *SqlDatastore) {{funcName "Save" .Type}}(ctx context.Context, object *models.{{.Type}}) error {
return ds.db.Save(object).Error
}
{{- $type := .Type}}
{{ range $idx, $key := .Keys -}}
{{ $fn := (print "Delete" $type $key.FuncName) -}}
// {{$fn}} soft-deletes the record by its key ({{$key.CallParams}}).
func {{$fn}}(ctx context.Context, {{ $key.Args }}) error { return defaultDatastore().{{$fn}}(ctx, {{$key.CallParams}}) }
func (ds *SqlDatastore) {{$fn}}(ctx context.Context, {{ $key.Args }}) error {
return ds.db.{{ $key.WhereClause }}.Delete(&models.{{$type}}{}).Error
}
{{ end }}
// Delete{{.Type}} soft-deletes the record.
func {{funcName "Delete" .Type}}(ctx context.Context, record *models.{{.Type}}) error { return defaultDatastore().{{funcName "Delete" .Type}}(ctx, record) }
func (ds *SqlDatastore) {{funcName "Delete" .Type}}(ctx context.Context, record *models.{{.Type}}) error {
return ds.db.Delete(record).Error
}
{{- $type := .Type}}
{{ range $idx, $key := .Keys -}}
{{ $getFn := (print "Get" $type $key.FuncName) -}}
// {{$getFn}} gets an instance of {{$type}} by its key ({{$key.CallParams}}).
func {{$getFn}}(ctx context.Context, {{ $key.Args }}) (*models.{{$type}}, error) { return defaultDatastore().{{$getFn}}(ctx, {{$key.CallParams}}) }
func (ds *SqlDatastore) {{$getFn}}(ctx context.Context, {{ $key.Args }}) (*models.{{$type}}, error) {
record := models.{{$type}}{}
if err := ds.db.{{ $key.WhereClause }}.First(&record).Error; err != nil {
return nil, err
}
return &record, nil
}
{{ $existsFn := (print "Exists" $type $key.FuncName) -}}
// {{$existsFn}} checks to see if an instance of {{$type}} exists by its key ({{$key.CallParams}}).
func {{$existsFn}}(ctx context.Context, {{ $key.Args }}) (bool, error) { return defaultDatastore().{{$existsFn}}(ctx, {{$key.CallParams}}) }
func (ds *SqlDatastore) {{$existsFn}}(ctx context.Context, {{ $key.Args }}) (bool, error) {
return recordToExists(ds.{{$getFn}}(ctx, {{ $key.CallParams }}))
}
{{ end }}
{{- end }}
func recordToExists(_ interface{}, err error) (bool, error) {
if err != nil {
if gorm.IsRecordNotFoundError(err) {
return false, nil
}
return false, err
}
return true, nil
}
`))
var daoTestTemplate = template.Must(template.New("").Funcs(
template.FuncMap{
"funcName": functionNameGen,
},
).Parse(`// Copyright {{ .Timestamp.Year }} the Service Broker Project Authors.
//
// 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.
// Code generated by go generate; DO NOT EDIT.
package db_service
import (
"context"
"testing"
"time"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/jinzhu/gorm"
)
func newInMemoryDatastore(t *testing.T) *SqlDatastore {
testDb, err := gorm.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("Error opening test database %s", err)
}
{{range .Models}}testDb.CreateTable(models.{{.Type}}{})
{{end}}
return &SqlDatastore{db: testDb}
}
{{- range .Models}}
func create{{.Type}}Instance() ({{.PrimaryKeyType}}, models.{{.Type}}) {
testPk := {{.PrimaryKeyType}}(42)
instance := models.{{.Type}}{}
instance.ID = testPk
{{range $k, $v := .ExampleFields}} instance.{{$k}} = {{ printf "%#v" $v}}
{{end}}
return testPk, instance
}
func ensure{{.Type}}FieldsMatch(t *testing.T, expected, actual *models.{{.Type}}) {
{{range $k, $v := .ExampleFields}}
if expected.{{$k}} != actual.{{$k}} {
t.Errorf("Expected field {{$k}} to be %#v, got %#v", expected.{{$k}}, actual.{{$k}})
}
{{end}}
}
func TestSqlDatastore_{{.Type}}DAO(t *testing.T) {
ds := newInMemoryDatastore(t)
testPk, instance := create{{.Type}}Instance()
testCtx := context.Background()
// on startup, there should be no objects to find or delete
exists, err := ds.{{funcName "Exists" .Type .PrimaryKeyField}}(testCtx, testPk)
ensureExistance(t, false, exists, err)
if _, err := ds.{{funcName "Get" .Type .PrimaryKeyField}}(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing PK got %v", err)
}
// Should be able to create the item
beforeCreation := time.Now()
if err := ds.{{funcName "Create" .Type}}(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.{{funcName "Get" .Type .PrimaryKeyField}}(testCtx, testPk)
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensure{{.Type}}FieldsMatch(t, &instance, ret)
// we should be able to update the item and it will have a new updated time
if err := ds.{{funcName "Save" .Type}}(testCtx, ret); err != nil {
t.Errorf("Expected no error trying to get update %#v , got: %v", ret, err)
}
if !ret.UpdatedAt.After(ret.CreatedAt) {
t.Errorf("Expected update time to be after create time after update, got update: %#v create: %#v", ret.UpdatedAt, ret.CreatedAt)
}
// after deleting the item we should not be able to get it
if err := ds.{{funcName "Delete" .Type .PrimaryKeyField}}(testCtx, testPk); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
if _, err := ds.{{funcName "Get" .Type .PrimaryKeyField}}(testCtx, testPk); err != gorm.ErrRecordNotFound {
t.Errorf("Expected ErrRecordNotFound after delete but got %v", err)
}
}
{{- $type := .Type}}{{ $pk := .PrimaryKeyField }}
{{ range $idx, $key := .Keys -}}
{{ $fn := (print "Get" $type $key.FuncName) -}}
func TestSqlDatastore_{{$fn}}(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := create{{$type}}Instance()
testCtx := context.Background()
if _, err := ds.{{$fn}}(testCtx, {{$key.ExampleArgs "instance"}}); err != gorm.ErrRecordNotFound {
t.Errorf("Expected an ErrRecordNotFound trying to get non-existing record got %v", err)
}
beforeCreation := time.Now()
if err := ds.{{funcName "Create" $type}}(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
afterCreation := time.Now()
// after creation we should be able to get the item
ret, err := ds.{{$fn}}(testCtx, {{$key.ExampleArgs "instance"}})
if err != nil {
t.Errorf("Expected no error trying to get saved item, got: %v", err)
}
if ret.CreatedAt.Before(beforeCreation) || ret.CreatedAt.After(afterCreation) {
t.Errorf("Expected creation time to be between %v and %v got %v", beforeCreation, afterCreation, ret.CreatedAt)
}
if !ret.UpdatedAt.Equal(ret.CreatedAt) {
t.Errorf("Expected initial update time to equal creation time, but got update: %v, create: %v", ret.UpdatedAt, ret.CreatedAt)
}
// Ensure non-gorm fields were deserialized correctly
ensure{{$type}}FieldsMatch(t, &instance, ret)
}
{{ $fn := (print "Exists" $type $key.FuncName) -}}
func TestSqlDatastore_{{$fn}}(t *testing.T) {
ds := newInMemoryDatastore(t)
_, instance := create{{$type}}Instance()
testCtx := context.Background()
exists, err := ds.{{$fn}}(testCtx, {{$key.ExampleArgs "instance"}})
ensureExistance(t, false, exists, err)
if err := ds.{{funcName "Create" $type}}(testCtx, &instance); err != nil {
t.Errorf("Expected to be able to create the item %#v, got error: %s", instance, err)
}
exists, err = ds.{{$fn}}(testCtx, {{$key.ExampleArgs "instance"}})
ensureExistance(t, true, exists, err)
if err := ds.{{funcName "Delete" $type}}(testCtx, &instance); err != nil {
t.Errorf("Expected no error when deleting by pk got: %v", err)
}
// we should be able to see that it was soft-deleted
exists, err = ds.{{$fn}}(testCtx, {{$key.ExampleArgs "instance"}})
ensureExistance(t, false, exists, err)
}
{{ end }}
{{- end }}
func ensureExistance(t *testing.T, expected, actual bool, err error) {
if err != nil {
t.Fatalf("Expected err to be nil, got %v", err)
}
if expected != actual {
t.Fatalf("Expected exists to be %t got %t", expected, actual)
}
}
`))
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/db_service.go | db_service/db_service.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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.
//go:generate go run dao_generator.go
package db_service
import (
"fmt"
"sync"
"code.cloudfoundry.org/lager"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var DbConnection *gorm.DB
var once sync.Once
// Instantiates the db connection and runs migrations
func New(logger lager.Logger) *gorm.DB {
once.Do(func() {
DbConnection = SetupDb(logger)
if err := RunMigrations(DbConnection); err != nil {
panic(fmt.Sprintf("Error migrating database: %s", err.Error()))
}
})
return DbConnection
}
// defaultDatastore gets the default datastore for the given default database
// instantiated in New(). In the future, all accesses of DbConnection will be
// done through SqlDatastore and it will become the globally shared instance.
func defaultDatastore() *SqlDatastore {
return &SqlDatastore{db: DbConnection}
}
type SqlDatastore struct {
db *gorm.DB
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/vcap.go | db_service/vcap.go | // Copyright 2019 the Service Broker Project Authors.
//
// 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 db_service
import (
"encoding/json"
"fmt"
"net/url"
"os"
"github.com/spf13/viper"
)
type VcapService struct {
BindingName string `json:"binding_name"` // The name assigned to the service binding by the user.
InstanceName string `json:"instance_name"` // The name assigned to the service instance by the user.
Name string `json:"name"` // The binding_name if it exists; otherwise the instance_name.
Label string `json:"label"` // The name of the service offering.
Tags []string `json:"tags"` // An array of strings an app can use to identify a service instance.
Plan string `json:"plan"` // The service plan selected when the service instance was created.
Credentials map[string]interface{} `json:"credentials"` // The service-specific credentials needed to access the service instance.
}
func UseVcapServices() error {
vcapData, vcapExists := os.LookupEnv("VCAP_SERVICES")
// CloudFoundry provides an empty VCAP_SERVICES hash by default
if !vcapExists || vcapData == "{}" {
return nil
}
vcapService, err := ParseVcapServices(vcapData)
if err != nil {
return fmt.Errorf("Error parsing VCAP_SERVICES: %s", err)
}
return SetDatabaseCredentials(vcapService)
}
func SetDatabaseCredentials(vcapService VcapService) error {
u, err := url.Parse(coalesce(vcapService.Credentials["uri"]))
if err != nil {
return fmt.Errorf("Error parsing credentials uri field: %s", err)
}
// Set up database credentials using environment variables
viper.Set(dbTypeProp, DbTypeMysql)
viper.Set(dbHostProp, coalesce(vcapService.Credentials["host"], vcapService.Credentials["hostname"]))
viper.Set(dbUserProp, coalesce(u.User.Username(), vcapService.Credentials["Username"], vcapService.Credentials["username"]))
if pw, _ := u.User.Password(); pw != "" {
viper.Set(dbPassProp, coalesce(pw, vcapService.Credentials["Password"], vcapService.Credentials["password"]))
} else {
viper.Set(dbPassProp, coalesce(vcapService.Credentials["Password"], vcapService.Credentials["password"]))
}
viper.Set(dbNameProp, coalesce(vcapService.Credentials["database_name"], vcapService.Credentials["name"]))
// If database is provided by gcp service broker, retrieve the client_cert, ca_cert and client_key fields
if contains(vcapService.Tags, "gcp") {
viper.Set(caCertProp, vcapService.Credentials["CaCert"])
viper.Set(clientCertProp, vcapService.Credentials["ClientCert"])
viper.Set(clientKeyProp, vcapService.Credentials["ClientKey"])
}
return nil
}
// Return first non-null string in list of arguments
func coalesce(credentials ...interface{}) string {
for _, credential := range credentials {
if credential != nil {
switch credential.(type) {
case int:
return fmt.Sprintf("%d", credential)
default:
return fmt.Sprintf("%v", credential)
}
}
}
return ""
}
func ParseVcapServices(vcapServicesData string) (VcapService, error) {
var vcapMap map[string][]VcapService
err := json.Unmarshal([]byte(vcapServicesData), &vcapMap)
if err != nil {
return VcapService{}, fmt.Errorf("Error unmarshalling VCAP_SERVICES: %s", err)
}
for _, vcapArray := range vcapMap {
vcapService, err := findMySqlTag(vcapArray, "mysql")
if err != nil {
return VcapService{}, fmt.Errorf("Error finding MySQL tag: %s", err)
}
return vcapService, nil
}
return VcapService{}, fmt.Errorf("Error parsing VCAP_SERVICES")
}
// whether a given string array arr contains string key
func contains(arr []string, key string) bool {
for _, n := range arr {
if key == n {
return true
}
}
return false
}
// return the index of the VcapService with a tag of "mysql" in the list of VcapServices, fail if we find more or fewer than 1
func findMySqlTag(vcapServices []VcapService, key string) (VcapService, error) {
index := -1
count := 0
for i, vcapService := range vcapServices {
if contains(vcapService.Tags, key) {
count += 1
index = i
}
}
if count != 1 {
return VcapService{}, fmt.Errorf("The variable VCAP_SERVICES must have one VCAP service with a tag of %s. There are currently %d VCAP services with the tag %s.", "'mysql'", count, "'mysql'")
}
return vcapServices[index], nil
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/models/historical_db.go | db_service/models/historical_db.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 models
import (
"time"
"github.com/jinzhu/gorm"
)
// This file contains versioned models for the database so we
// can do proper tracking through gorm.
//
// If you need to change a model you MUST make a copy here and update the
// reference to the new model in db.go and add a migration path in the
// db_service package.
// ServiceBindingCredentialsV1 holds credentials returned to the users after
// binding to a service.
type ServiceBindingCredentialsV1 struct {
gorm.Model
OtherDetails string `gorm:"type:text"`
ServiceId string
ServiceInstanceId string
BindingId string
}
// TableName returns a consistent table name (`service_binding_credentials`) for
// gorm so multiple structs from different versions of the database all operate
// on the same table.
func (ServiceBindingCredentialsV1) TableName() string {
return "service_binding_credentials"
}
// ServiceInstanceDetailsV1 holds information about provisioned services.
type ServiceInstanceDetailsV1 struct {
ID string `gorm:"primary_key;type:varchar(255);not null"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
Name string
Location string
Url string
OtherDetails string `gorm:"type:text"`
ServiceId string
PlanId string
SpaceGuid string
OrganizationGuid string
}
// TableName returns a consistent table name (`service_instance_details`) for
// gorm so multiple structs from different versions of the database all operate
// on the same table.
func (ServiceInstanceDetailsV1) TableName() string {
return "service_instance_details"
}
// ServiceInstanceDetailsV2 holds information about provisioned services.
type ServiceInstanceDetailsV2 struct {
ID string `gorm:"primary_key;type:varchar(255);not null"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
Name string
Location string
Url string
OtherDetails string `gorm:"type:text"`
ServiceId string
PlanId string
SpaceGuid string
OrganizationGuid string
// OperationType holds a string corresponding to what kind of operation
// OperationId is referencing. The object is "locked" for editing if
// an operation is pending.
OperationType string
// OperationId holds a string referencing an operation specific to a broker.
// Operations in GCP all have a unique ID.
// The OperationId will be cleared after a successful operation.
// This string MAY be sent to users and MUST NOT leak confidential information.
OperationId string `gorm:"type:varchar(1024)"`
}
// TableName returns a consistent table name (`service_instance_details`) for
// gorm so multiple structs from different versions of the database all operate
// on the same table.
func (ServiceInstanceDetailsV2) TableName() string {
return "service_instance_details"
}
// ProvisionRequestDetailsV1 holds user-defined properties passed to a call
// to provision a service.
type ProvisionRequestDetailsV1 struct {
gorm.Model
ServiceInstanceId string
// is a json.Marshal of models.ProvisionDetails
RequestDetails string
}
// TableName returns a consistent table name (`provision_request_details`) for
// gorm so multiple structs from different versions of the database all operate
// on the same table.
func (ProvisionRequestDetailsV1) TableName() string {
return "provision_request_details"
}
// ProvisionRequestDetailsV2 holds user-defined properties passed to a call
// to provision a service.
type ProvisionRequestDetailsV2 struct {
gorm.Model
ServiceInstanceId string
// is a json.Marshal of models.ProvisionDetails
RequestDetails string `gorm:"type:text"`
}
// TableName returns a consistent table name (`provision_request_details`) for
// gorm so multiple structs from different versions of the database all operate
// on the same table.
func (ProvisionRequestDetailsV2) TableName() string {
return "provision_request_details"
}
// MigrationV1 represents the mgirations table. It holds a monotonically
// increasing number that gets incremented with every database schema revision.
type MigrationV1 struct {
gorm.Model
MigrationId int `gorm:"type:int(10)"`
}
// TableName returns a consistent table name (`migrations`) for gorm so
// multiple structs from different versions of the database all operate on the
// same table.
func (MigrationV1) TableName() string {
return "migrations"
}
// CloudOperationV1 holds information about the status of Google Cloud
// long-running operations.
// As-of version 4.1.0, this table is no longer necessary.
type CloudOperationV1 struct {
gorm.Model
Name string
Status string
OperationType string
ErrorMessage string `gorm:"type:text"`
InsertTime string
StartTime string
TargetId string
TargetLink string
ServiceId string
ServiceInstanceId string
}
// TableName returns a consistent table name (`cloud_operations`) for gorm so
// multiple structs from different versions of the database all operate on the
// same table.
func (CloudOperationV1) TableName() string {
return "cloud_operations"
}
// PlanDetailsV1 is a table that was deprecated in favor of using Environment
// variables. It only remains for ORM migrations and the ability for existing
// users to export their plans.
type PlanDetailsV1 struct {
ID string `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
ServiceId string
Name string
Features string `sql:"type:text"`
}
// TableName returns a consistent table name (`plan_details`) for gorm so
// multiple structs from different versions of the database all operate on the
// same table.
func (PlanDetailsV1) TableName() string {
return "plan_details"
}
// TerraformDeploymentV1 describes the state of a Terraform resource deployment.
type TerraformDeploymentV1 struct {
ID string `gorm:"primary_key",sql:"type:varchar(1024)"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
// Workspace contains a JSON serialized version of the Terraform workspace.
Workspace string `sql:"type:text"`
// LastOperationType describes the last operation being performed on the resource.
LastOperationType string
// LastOperationState holds one of the following strings "in progress", "succeeded", "failed".
// These mirror the OSB API.
LastOperationState string
// LastOperationMessage is a description that can be passed back to the user.
LastOperationMessage string
}
// TableName returns a consistent table name (`tf_deployment`) for gorm so
// multiple structs from different versions of the database all operate on the
// same table.
func (TerraformDeploymentV1) TableName() string {
return "terraform_deployments"
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/db_service/models/db.go | db_service/models/db.go | // Copyright 2018 the Service Broker Project Authors.
//
// 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 models
import (
"encoding/json"
)
const (
// The following operation types are used as part of the OSB process.
// The types correspond to asynchronous provision/deprovision/update calls
// and will exist on a ServiceInstanceDetails with an operation ID that can be
// used to look up the state of an operation.
ProvisionOperationType = "provision"
DeprovisionOperationType = "deprovision"
UpdateOperationType = "update"
ClearOperationType = ""
)
// ServiceBindingCredentials holds credentials returned to the users after
// binding to a service.
type ServiceBindingCredentials ServiceBindingCredentialsV1
// ServiceInstanceDetails holds information about provisioned services.
type ServiceInstanceDetails ServiceInstanceDetailsV2
// SetOtherDetails marshals the value passed in into a JSON string and sets
// OtherDetails to it if marshalling was successful.
func (si *ServiceInstanceDetails) SetOtherDetails(toSet interface{}) error {
out, err := json.Marshal(toSet)
if err != nil {
return err
}
si.OtherDetails = string(out)
return nil
}
// GetOtherDetails returns an unmarshalls the OtherDetails field into the given
// struct. An empty OtherDetails field does not get unmarshalled and does not error.
func (si ServiceInstanceDetails) GetOtherDetails(v interface{}) error {
if si.OtherDetails == "" {
return nil
}
return json.Unmarshal([]byte(si.OtherDetails), v)
}
// ProvisionRequestDetails holds user-defined properties passed to a call
// to provision a service.
type ProvisionRequestDetails ProvisionRequestDetailsV1
// Migration represents the mgirations table. It holds a monotonically
// increasing number that gets incremented with every database schema revision.
type Migration MigrationV1
// CloudOperation holds information about the status of Google Cloud
// long-running operations.
type CloudOperation CloudOperationV1
// TerraformDeployment holds Terraform state and plan information for resources
// that use that execution system.
type TerraformDeployment TerraformDeploymentV1
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/util/data_structures.go | provider/pkg/util/data_structures.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package util
import (
"cmp"
"iter"
"slices"
"github.com/pulumi/pulumi/sdk/v3/go/common/slice"
)
// GetInnerMap returns a map nested inside another. It traverses the list of keys, such that in
// {a: {b: {c: 1}}}, GetInnerMap(m, "a", "b") returns {c: 1}.
// Its purpose is to let callers avoid the repeated `if ..., ok` double check of does the key
// exist, and is the value a map, at each level.
func GetInnerMap(m map[string]any, keys ...string) (map[string]any, bool) {
cur := m
for i, key := range keys {
val, ok := cur[key]
if !ok {
return nil, false
}
if i == len(keys)-1 {
if valMap, ok := val.(map[string]any); ok {
return valMap, true
}
}
cur, ok = val.(map[string]any)
if !ok {
return nil, false
}
}
return nil, false
}
// UnsortedKeys returns the keys of a map in an arbitrary order.
func UnsortedKeys[K comparable, V any](m map[K]V) []K {
keys := slice.Prealloc[K](len(m))
for key := range m {
keys = append(keys, key)
}
return keys
}
// SortedKeys returns the keys of a map in sorted order.
func SortedKeys[K cmp.Ordered, V any](m map[K]V) []K {
keys := UnsortedKeys(m)
slices.Sort(keys)
return keys
}
// MapOrdered returns a sequence of key-value pairs from a map, ordered by key.
// Example usage:
//
// for key, value := range util.MapOrdered(m) {
// ...
// }
func MapOrdered[K cmp.Ordered, V any](m map[K]V) iter.Seq2[K, V] {
keys := SortedKeys(m)
return func(yield func(K, V) bool) {
for _, key := range keys {
if !yield(key, m[key]) {
return
}
}
}
}
// RemoveFromSlice removes the given value from a slice, if found. It returns a new slice.
// It will only remove the FIRST value if there are multiple occurrences.
func RemoveFromSlice[T comparable](slice []T, value T) []T {
for i, v := range slice {
if v == value {
return append(slice[:i], slice[i+1:]...)
}
}
return slice
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/util/data_structures_test.go | provider/pkg/util/data_structures_test.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package util
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetInnerMap(t *testing.T) {
t.Run("no keys", func(t *testing.T) {
m := map[string]any{
"a": "b",
}
_, ok := GetInnerMap(m)
assert.False(t, ok)
})
t.Run("empty map", func(t *testing.T) {
m := map[string]any{}
_, ok := GetInnerMap(m, "a", "b")
assert.False(t, ok)
})
t.Run("key has no map value", func(t *testing.T) {
m := map[string]any{
"a": 1,
}
_, ok := GetInnerMap(m, "a")
assert.False(t, ok)
})
t.Run("single key", func(t *testing.T) {
m := map[string]any{
"a": map[string]any{"b": 1},
}
inner, ok := GetInnerMap(m, "a")
assert.True(t, ok)
assert.Equal(t, map[string]any{"b": 1}, inner)
})
t.Run("multiple keys", func(t *testing.T) {
m := map[string]any{
"a": map[string]any{"b": map[string]any{"c": 1}},
}
inner, ok := GetInnerMap(m, "a", "b")
assert.True(t, ok)
assert.Equal(t, map[string]any{"c": 1}, inner)
})
t.Run("multiple keys, one has no map value", func(t *testing.T) {
m := map[string]any{
"a": map[string]any{"b": 1},
}
_, ok := GetInnerMap(m, "a", "b", "c")
assert.False(t, ok)
})
}
func TestRemoveFromSlice(t *testing.T) {
t.Run("empty slice", func(t *testing.T) {
s := []int{}
s = RemoveFromSlice(s, 1)
assert.Equal(t, []int{}, s)
})
t.Run("value not found", func(t *testing.T) {
s := []int{1, 2, 3}
s = RemoveFromSlice(s, 4)
assert.Equal(t, []int{1, 2, 3}, s)
})
t.Run("value found", func(t *testing.T) {
s := []int{1, 2, 3}
s = RemoveFromSlice(s, 2)
assert.Equal(t, []int{1, 3}, s)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/util/retry_test.go | provider/pkg/util/retry_test.go | // Copyright 2025, Pulumi Corporation. All rights reserved.
package util
import (
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestPollOperation(t *testing.T) {
t.Parallel()
t.Run("SuccessBeforeTimeout", func(t *testing.T) {
t.Parallel()
operation := func() (bool, error) {
return true, nil
}
err := RetryOperation(2*time.Second, 500*time.Millisecond, "test operation", operation)
assert.NoError(t, err, "expected no error")
})
t.Run("TimesOut", func(t *testing.T) {
t.Parallel()
operation := func() (bool, error) {
return false, nil
}
err := RetryOperation(1*time.Second, 500*time.Millisecond, "test operation", operation)
assert.Error(t, err, "expected timeout error")
assert.EqualError(t, err, "timed out during test operation after 1s")
})
t.Run("ErrorDuringOperation", func(t *testing.T) {
t.Parallel()
expectedErr := errors.New("operation error")
operation := func() (bool, error) {
return true, expectedErr
}
err := RetryOperation(2*time.Second, 500*time.Millisecond, "test operation", operation)
assert.Error(t, err, "expected operation error")
assert.True(t, errors.Is(err, expectedErr), "expected error to match")
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/util/retry.go | provider/pkg/util/retry.go | // Copyright 2025, Pulumi Corporation. All rights reserved.
package util
import (
"fmt"
"time"
)
// RetryOperation repeats the given operation until it succeeds, fails, or times out.
// The given operation should return true if the operation is done, false if it should be retried.
func RetryOperation(timeout time.Duration, interval time.Duration, description string, operation func() (bool, error)) error {
timeoutChan := time.After(timeout)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-timeoutChan:
return fmt.Errorf("timed out during %s after %s", description, timeout)
case <-ticker.C:
done, err := operation()
if err != nil {
return fmt.Errorf("error during %s: %w", description, err)
}
if done {
return nil
}
}
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/parser.go | provider/pkg/tle/parser.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
import (
"errors"
"fmt"
"strings"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// ParseResult provides the result of calling Parse on a string.
type ParseResult struct {
LeftSquareBracketToken *Token
Expression Value
RightSquareBracketToken *Token
}
type tleGenVisitor struct {
builder strings.Builder
}
func (t *tleGenVisitor) VisitArrayAccessValue(value *ArrayAccessValue) error {
if err := value.source.Accept(t); err != nil {
return err
}
_, _ = t.builder.WriteString("[")
if err := value.indexValue.Accept(t); err != nil {
return err
}
_, _ = t.builder.WriteString("]")
return nil
}
func (t *tleGenVisitor) VisitFunctionCallValue(value *FunctionCallValue) error {
// WriteString never returns a non-nil error
_, _ = t.builder.WriteString(value.NameToken.stringValue)
_, _ = t.builder.WriteString("(")
for i, a := range value.ArgumentExpressions {
if err := a.Accept(t); err != nil {
return err
}
if i < len(value.ArgumentExpressions)-1 {
_, _ = t.builder.WriteString(",")
}
}
t.builder.WriteString(")")
return nil
}
func (t *tleGenVisitor) VisitNumberValue(value *NumberValue) error {
t.builder.WriteString(value.token.stringValue)
return nil
}
func (t *tleGenVisitor) VisitPropertyAccessValue(value *PropertyAccessValue) error {
if err := value.source.Accept(t); err != nil {
return err
}
_, _ = t.builder.WriteString(fmt.Sprintf(".%s", value.nameToken.stringValue))
return nil
}
func (t *tleGenVisitor) VisitStringValue(value *StringValue) error {
_, _ = t.builder.WriteString(quote(value.token.stringValue))
return nil
}
// ToTemplateExpressionString does the opposite of Parse, i.e.
// takes a TLE parse tree and converts it to a corresponding TLE string.
// Note it is assumed that value contains at least one TLE expression,
// i.e. its not just a StringValue.
func ToTemplateExpressionString(value Value) (string, error) {
gen := &tleGenVisitor{}
_, _ = gen.builder.WriteString("[")
if err := value.Accept(gen); err != nil {
return "", err
}
_, _ = gen.builder.WriteString("]")
return quote(gen.builder.String()), nil
}
// Parse takes a string which may potentially be a TLE expression and generates the
// AST for it.
func Parse(s string) (*ParseResult, error) {
return parseString(quote(s))
}
func parseString(quotedStringValue string) (*ParseResult, error) {
contract.Assert(1 <= len(quotedStringValue)) // TLE strings must be at least 1 character
// The first character in the TLE string to parse must be a quote character
contract.Assert(isQuoteCharacter(quotedStringValue[0]))
var leftSquareBracketToken *Token
var expression Value
var rightSquareBracketToken *Token
if 3 <= len(quotedStringValue) && quotedStringValue[1:2] == "[[" {
expression = NewStringValue(CreateQuotedString(0, quotedStringValue))
} else {
tokenizer := fromString(quotedStringValue)
tokenizer.Next()
if tokenizer.Current() == nil || tokenizer.Current().GetType() != LeftSquareBracket {
// This is just a plain old string (no brackets). Mark its expression as being
// the string value.
expression = NewStringValue(CreateQuotedString(0, quotedStringValue))
} else {
leftSquareBracketToken = tokenizer.Current()
tokenizer.Next()
if tokenizer.Current() != nil &&
tokenizer.Current().GetType() != Literal &&
tokenizer.Current().GetType() != RightSquareBracket {
return nil, fmt.Errorf("expected a literal value: %s:%v",
quotedStringValue,
tokenizer.Current().Span().getStartIndex())
}
var err error
expression, err = parseExpression(tokenizer)
if err != nil {
return nil, fmt.Errorf("failed to parse expression '%s': %w", quotedStringValue, err)
}
for tokenizer.Current() != nil {
if tokenizer.Current().GetType() == RightSquareBracket {
rightSquareBracketToken = tokenizer.Current()
tokenizer.Next()
break
} else {
return nil, fmt.Errorf("expected end of string: %s:%v",
quotedStringValue, tokenizer.Current().Span().getStartIndex())
}
}
if rightSquareBracketToken != nil {
if tokenizer.Current() != nil {
return nil, fmt.Errorf(
"nothing should exist after the closing ']' except for whitespace, %s:%v",
quotedStringValue,
tokenizer.Current().Span().getStartIndex(),
)
}
} else {
return nil, fmt.Errorf("expected a right square bracket (']'), %s:%v",
quotedStringValue,
len(quotedStringValue)-1,
)
}
if expression == nil {
errorSpan := &leftSquareBracketToken.span
if rightSquareBracketToken != nil {
errorSpan = union(errorSpan, &rightSquareBracketToken.span)
}
return nil, fmt.Errorf("expected a function of property expression, %s:%v",
quotedStringValue,
errorSpan.getStartIndex(),
)
}
}
}
return &ParseResult{
LeftSquareBracketToken: leftSquareBracketToken,
Expression: expression,
RightSquareBracketToken: rightSquareBracketToken,
}, nil
}
func parseExpression(tokenizer *Tokenizer) (Value, error) {
var expression Value
if tokenizer.Current() != nil {
var rootExpression Value // Initial expression
token := tokenizer.Current()
tokenType := token.GetType()
if tokenType == Literal {
var err error
rootExpression, err = parseFunctionCall(tokenizer)
if err != nil {
return nil, err
}
} else if tokenType == QuotedString {
if !strings.HasSuffix(token.stringValue, string(token.stringValue[0])) {
return nil, fmt.Errorf("a constant string is missing an end quote: %d", token.span.getStartIndex())
}
rootExpression = NewStringValue(*token)
tokenizer.Next()
} else if tokenType == Number {
rootExpression = NewNumberValue(*token)
tokenizer.Next()
} else if tokenType != RightSquareBracket && tokenType != Comma {
return nil, fmt.Errorf("template language expressions must start with a function: %d", token.span.getStartIndex())
}
if rootExpression == nil {
return nil, nil
}
expression = rootExpression
} else {
return nil, nil
}
// Check for property or array accesses off of the root expression
for tokenizer.Current() != nil {
if tokenizer.Current().GetType() == Period {
periodToken := tokenizer.Current()
tokenizer.Next()
var propertyNameToken *Token
var errorSpan Span
if tokenizer.Current() != nil {
if tokenizer.Current().GetType() == Literal {
propertyNameToken = tokenizer.Current()
tokenizer.Next()
} else {
errorSpan = tokenizer.Current().Span()
tokenType := tokenizer.Current().GetType()
if tokenType != RightParenthesis &&
tokenType != RightSquareBracket &&
tokenType != Comma {
tokenizer.Next()
}
}
} else {
errorSpan = periodToken.Span()
}
if propertyNameToken == nil {
return nil, fmt.Errorf("expected a literal value in span at %d", errorSpan.getStartIndex())
}
expression = NewPropertyAccessValue(expression, *periodToken, *propertyNameToken)
} else if tokenizer.Current().GetType() == LeftSquareBracket {
leftSquareBracketToken := tokenizer.Current()
tokenizer.Next()
indexValue, err := parseExpression(tokenizer)
if err != nil {
return nil, err
}
var rightSquareBracketToken *Token
if tokenizer.Current() != nil && tokenizer.Current().GetType() == RightSquareBracket {
rightSquareBracketToken = tokenizer.Current()
tokenizer.Next()
}
if leftSquareBracketToken == nil || rightSquareBracketToken == nil {
return nil, fmt.Errorf("malformed array offset specification near: %d", indexValue.Span().getStartIndex())
}
expression = NewArrayAccessValue(expression, *leftSquareBracketToken, indexValue, *rightSquareBracketToken)
} else {
break
}
}
return expression, nil
}
func parseFunctionCall(tokenizer *Tokenizer) (*FunctionCallValue, error) {
contract.Assert(tokenizer != nil)
contract.Assert(tokenizer.Current() != nil)
contract.Assert(Literal == tokenizer.Current().GetType())
var namespaceToken, nameToken, periodToken *Token
firstToken := tokenizer.Current()
tokenizer.Next()
// Check for <namespace>.<functionname>
if tokenizer.Current() != nil && tokenizer.Current().GetType() == Period {
// It's a user-defined function because it has a namespace before the function name
periodToken = tokenizer.Current()
namespaceToken = firstToken
tokenizer.Next()
// Get the function name following the period
if tokenizer.HasCurrent() && tokenizer.Current().GetType() == Literal {
nameToken = tokenizer.Current()
tokenizer.Next()
} else {
return nil, fmt.Errorf("Expected user-defined function name: %v", periodToken.Span().getStartIndex())
}
} else {
nameToken = firstToken
}
var leftParenthesisToken, rightParanthesisToken *Token
var commaTokens []*Token
var argumentExpressions []Value
if tokenizer.Current() != nil {
for tokenizer.Current() != nil {
if tokenizer.Current().GetType() == LeftParenthesis {
leftParenthesisToken = tokenizer.Current()
tokenizer.Next()
break
} else if tokenizer.Current().GetType() == RightSquareBracket {
return nil, fmt.Errorf("Missing function argument list: %d", nameToken.Span().getStartIndex())
} else {
return nil, fmt.Errorf("expected the end of the string: %d", nameToken.Span().getStartIndex())
}
}
} else {
return nil, fmt.Errorf("Missing function argument list: %d", nameToken.Span().getStartIndex())
}
if tokenizer.HasCurrent() {
expectingArgument := true
for tokenizer.Current() != nil {
if tokenizer.Current().GetType() == RightParenthesis || tokenizer.Current().GetType() == RightSquareBracket {
break
} else if expectingArgument {
expression, err := parseExpression(tokenizer)
if err != nil {
return nil, err
}
if expression == nil && tokenizer.HasCurrent() && tokenizer.Current().GetType() == Comma {
return nil, errors.New("expected a constant string, function, or property expression")
}
argumentExpressions = append(argumentExpressions, expression)
expectingArgument = false
} else if tokenizer.Current().GetType() == Comma {
expectingArgument = true
commaTokens = append(commaTokens, tokenizer.Current())
tokenizer.Next()
} else {
return nil, errors.New("expected a comma (',')")
}
}
} else if leftParenthesisToken != nil {
return nil, fmt.Errorf("expected a right parenthesis (')')")
}
if tokenizer.Current() != nil {
switch tokenizer.current.GetType() {
case RightParenthesis:
rightParanthesisToken = tokenizer.Current()
tokenizer.Next()
case RightSquareBracket:
if leftParenthesisToken != nil {
return nil, fmt.Errorf("expected a right parenthesis (')')")
}
}
}
return &FunctionCallValue{
NamespaceToken: namespaceToken,
PeriodToken: periodToken,
NameToken: *nameToken,
LeftParenthesisToken: leftParenthesisToken,
CommaTokens: commaTokens,
ArgumentExpressions: argumentExpressions,
RightParenthesisToken: rightParanthesisToken,
}, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/basic.go | provider/pkg/tle/basic.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
import (
"strings"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
type BasicTokenType int
const (
leftCurlyBracket BasicTokenType = iota
rightCurlyBracket
leftSquareBracket
rightSquareBracket
leftParenthesis
rightParenthesis
underscore
period
dash
plus
comma
colon
singleQuote
doubleQuote
backslash
forwardSlash
asterisk
space
tab
newLine
carriageReturn
carriageReturnNewLine
letters
digits
unrecognized
)
var (
tokenLeftCurlyBracket = basicToken{"{", leftCurlyBracket}
tokenRightCurlyBracket = basicToken{"}", rightCurlyBracket}
tokenLeftSquareBracket = basicToken{"[", leftSquareBracket}
tokenRightSquareBracket = basicToken{"]", rightSquareBracket}
tokenLeftParenthesis = basicToken{"(", leftParenthesis}
tokenRightParenthesis = basicToken{")", rightParenthesis}
tokenUnderscore = basicToken{"_", underscore}
tokenPeriod = basicToken{".", period}
tokenDash = basicToken{"-", dash}
tokenPlus = basicToken{"+", plus}
tokenComma = basicToken{",", comma}
tokenColon = basicToken{":", colon}
tokenSingleQuote = basicToken{`'`, singleQuote}
tokenDoubleQuote = basicToken{`"`, doubleQuote}
tokenBackslash = basicToken{"\\", backslash}
tokenForwardSlash = basicToken{"/", forwardSlash}
tokenAsterisk = basicToken{"*", asterisk}
tokenSpace = basicToken{" ", space}
tokenTab = basicToken{"\t", tab}
tokenNewLine = basicToken{"\n", newLine}
tokenCarriageReturn = basicToken{"\r", carriageReturn}
tokenCarriageReturnNewLine = basicToken{"\r\n", carriageReturnNewLine}
)
// lettersFromText creates a Token from the provided text.
func lettersFromText(text string) basicToken {
return basicToken{text: text, typ: letters}
}
/**
* Create a digitsFromText Token from the provided text.
*/
func digitsFromText(text string) basicToken {
return basicToken{text: text, typ: digits}
}
/**
* Create an unrecognizedFromText Token from the provided text.
*/
func unrecognizedFromText(text string) basicToken {
return basicToken{text: text, typ: unrecognized}
}
/**
* Get whether the provided character is a letter or not.
*/
func isLetter(character byte) bool {
return ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z')
}
func isDigit(character byte) bool {
return '0' <= character && character <= '9'
}
type basicToken struct {
text string
typ BasicTokenType
}
func (t *basicToken) toString() string {
return t.text
}
func (t *basicToken) getType() BasicTokenType {
return t.typ
}
func newBasicTokenizer(text string) *basicTokenizer {
return &basicTokenizer{
text: text,
textIndex: -1,
textLength: len(text),
}
}
type basicTokenizer struct {
textLength int
textIndex int
currentToken *basicToken
text string
}
type TokenIterator interface {
HasStarted() bool
Current() *basicToken
MoveNext() bool
}
func (t *basicTokenizer) HasStarted() bool {
return t.textIndex >= 0
}
func (t *basicTokenizer) Current() *basicToken {
return t.currentToken
}
func (t *basicTokenizer) currentCharacter() (char byte, eof bool) {
if 0 <= t.textIndex && t.textIndex < t.textLength {
char = t.text[t.textIndex]
return
}
eof = true
return
}
func (t *basicTokenizer) nextCharacter() {
t.textIndex++
}
func (t *basicTokenizer) MoveNext() bool {
if !t.HasStarted() {
t.nextCharacter()
}
c, eof := t.currentCharacter()
if eof {
t.currentToken = nil
} else {
switch c {
case '{':
t.currentToken = &tokenLeftCurlyBracket
t.nextCharacter()
case '}':
t.currentToken = &tokenRightCurlyBracket
t.nextCharacter()
case '[':
t.currentToken = &tokenLeftSquareBracket
t.nextCharacter()
case ']':
t.currentToken = &tokenRightSquareBracket
t.nextCharacter()
case '(':
t.currentToken = &tokenLeftParenthesis
t.nextCharacter()
case ')':
t.currentToken = &tokenRightParenthesis
t.nextCharacter()
case '_':
t.currentToken = &tokenUnderscore
t.nextCharacter()
case '.':
t.currentToken = &tokenPeriod
t.nextCharacter()
case '-':
t.currentToken = &tokenDash
t.nextCharacter()
case '+':
t.currentToken = &tokenPlus
t.nextCharacter()
case ',':
t.currentToken = &tokenComma
t.nextCharacter()
case ':':
t.currentToken = &tokenColon
t.nextCharacter()
case '\'':
t.currentToken = &tokenSingleQuote
t.nextCharacter()
case '"':
t.currentToken = &tokenDoubleQuote
t.nextCharacter()
case '\\':
t.currentToken = &tokenBackslash
t.nextCharacter()
case '/':
t.currentToken = &tokenForwardSlash
t.nextCharacter()
case '*':
t.currentToken = &tokenAsterisk
t.nextCharacter()
case '\n':
t.currentToken = &tokenNewLine
t.nextCharacter()
case '\r':
t.nextCharacter()
var newC byte
newC, eof = t.currentCharacter()
if !eof && string(newC) == "\n" {
t.currentToken = &tokenCarriageReturnNewLine
t.nextCharacter()
} else {
t.currentToken = &tokenCarriageReturn
}
case ' ':
t.currentToken = &tokenSpace
t.nextCharacter()
case '\t':
t.currentToken = &tokenTab
t.nextCharacter()
default:
if isLetter(c) {
letters := lettersFromText(t.readWhile(isLetter))
t.currentToken = &letters
break
}
var cNew byte
cNew, _ = t.currentCharacter()
if isDigit(cNew) {
digits := digitsFromText(t.readWhile(isDigit))
t.currentToken = &digits
} else {
unrecognized := unrecognizedFromText(string(cNew))
t.currentToken = &unrecognized
t.nextCharacter()
}
}
}
return t.currentToken != nil
}
func (t *basicTokenizer) readWhile(condition func(character byte) bool) string {
var result string
res, _ := t.currentCharacter()
result = string(res)
t.nextCharacter()
_, eof := t.currentCharacter()
for !eof {
res, eof = t.currentCharacter()
if !condition(res) {
break
}
result += string(res)
t.nextCharacter()
}
return result
}
/**
* Read a JSON whitespace string from the provided tokenizer.
*/
func readWhitespace(iterator TokenIterator) []*basicToken {
var whitespaceTokens []*basicToken
for {
current := iterator.Current()
if current == nil {
return whitespaceTokens
}
switch current.getType() {
case space, tab, carriageReturn, newLine, carriageReturnNewLine:
whitespaceTokens = append(whitespaceTokens, current)
iterator.MoveNext()
default:
return whitespaceTokens
}
}
}
/**
* Read a JSON quoted string from the provided tokenizer. The tokenizer must be pointing at
* either a SingleQuote or DoubleQuote Token.
*
* Note that the returned quoted string may not end with a quote (if EOD is reached)
*/
func readQuotedString(iterator TokenIterator) []*basicToken {
startingToken := iterator.Current()
contract.Assert(startingToken != nil &&
(startingToken.getType() == singleQuote || startingToken.getType() == doubleQuote))
startQuote := startingToken
quotedStringTokens := []*basicToken{startQuote}
iterator.MoveNext()
escaped := false
var endQuote *basicToken
current := iterator.Current()
for endQuote == nil && current != nil {
quotedStringTokens = append(quotedStringTokens, current)
if escaped {
escaped = false
} else {
if current.getType() == backslash {
escaped = true
} else if current.getType() == startQuote.getType() {
endQuote = iterator.Current()
}
}
iterator.MoveNext()
current = iterator.Current()
}
return quotedStringTokens
}
/**
* Read a JSON number from the provided iterator. The iterator must be pointing at either a
* Dash or digitsFromText Token when this function is called.
*/
func readNumber(iterator TokenIterator) []*basicToken {
var numberBasicTokens []*basicToken
dashOrDigitsToken := iterator.Current()
if dashOrDigitsToken.getType() == dash {
// Negative sign
numberBasicTokens = append(numberBasicTokens, dashOrDigitsToken)
iterator.MoveNext()
}
digitsI := iterator.Current()
if digitsI != nil && digitsI.getType() == digits {
// Whole number digits
numberBasicTokens = append(numberBasicTokens, digitsI)
iterator.MoveNext()
}
decimal := iterator.Current()
if decimal != nil && decimal.getType() == period {
// Decimal point
numberBasicTokens = append(numberBasicTokens, decimal)
iterator.MoveNext()
fractionalDigits := iterator.Current()
if fractionalDigits != nil && fractionalDigits.getType() == digits {
// Fractional number digits
numberBasicTokens = append(numberBasicTokens, fractionalDigits)
iterator.MoveNext()
}
}
exponentLetter := iterator.Current()
if exponentLetter != nil {
if exponentLetter.getType() == letters && strings.ToLower(exponentLetter.toString()) == "e" {
// e
numberBasicTokens = append(numberBasicTokens, exponentLetter)
iterator.MoveNext()
exponentSign := iterator.Current()
if exponentSign != nil &&
(exponentSign.getType() == dash || exponentSign.getType() == plus) {
// Exponent number sign
numberBasicTokens = append(numberBasicTokens, exponentSign)
iterator.MoveNext()
}
exponentDigits := iterator.Current()
if exponentDigits != nil && exponentDigits.getType() == digits {
// Exponent number digits
numberBasicTokens = append(numberBasicTokens, exponentDigits)
iterator.MoveNext()
}
}
}
return numberBasicTokens
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/span.go | provider/pkg/tle/span.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
type Span struct {
startIndex int
length int
}
// Get the start index of this span.
func (s Span) getStartIndex() int {
return s.startIndex
}
// Get the getLength() of this span.
func (s Span) getLength() int {
return s.length
}
// Get the index directly after this span.
//
// If this span started at 3 and had a getLength() of 4 ([3,7)), then the after
// end index would be 7.
func (s Span) afterEndIndex() int {
return s.startIndex + s.getLength()
}
// Create a new span that is a union of this Span and the provided Span.
// If the provided Span is undefined, then this Span will be returned.
func (s Span) union(rhs *Span) *Span {
var result Span
if rhs != nil {
minStart := s.startIndex
if minStart > rhs.startIndex {
minStart = rhs.startIndex
}
maxAfterEndIndex := s.afterEndIndex()
if maxAfterEndIndex < rhs.afterEndIndex() {
maxAfterEndIndex = rhs.afterEndIndex()
}
result = Span{startIndex: minStart, length: maxAfterEndIndex - minStart}
} else {
result = s
}
return &result
}
// Create a new span that is a union of the given spans.
// If both are undefined, undefined will be returned
func union(lhs *Span, rhs *Span) *Span {
if lhs != nil {
return lhs.union(rhs)
}
if rhs != nil {
return rhs
}
return nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/tokenizer.go | provider/pkg/tle/tokenizer.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
import (
"strings"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
func NewTokenizer(basicTokenizer *basicTokenizer, text string) *Tokenizer {
return &Tokenizer{
basicTokenizer: basicTokenizer,
text: text,
}
}
type Tokenizer struct {
current *Token
currentTokenStartIndex int
text string
basicTokenizer *basicTokenizer
}
func fromString(stringValue string) *Tokenizer {
contract.Assert(stringValue != "")
contract.Assert(1 <= len(stringValue))
contract.Assert(isQuoteCharacter(stringValue[0]))
initialQuoteCharacter := stringValue[0]
trimmedLength := len(stringValue)
if strings.HasSuffix(stringValue, string(initialQuoteCharacter)) {
trimmedLength = len(stringValue) - 1
}
trimmedString := stringValue[1:trimmedLength]
return NewTokenizer(newBasicTokenizer(trimmedString), stringValue)
}
func (t *Tokenizer) HasStarted() bool {
return t.basicTokenizer.HasStarted()
}
func (t *Tokenizer) HasCurrent() bool {
return t.current != nil
}
func (t *Tokenizer) Current() *Token {
return t.current
}
func (t *Tokenizer) nextBasicToken() {
t.basicTokenizer.MoveNext()
}
func (t *Tokenizer) currentBasicToken() *basicToken {
return t.basicTokenizer.Current()
}
func (t *Tokenizer) ReadToken() *Token {
if !t.HasStarted() {
t.nextBasicToken()
} else if t.current != nil {
t.currentTokenStartIndex += t.current.Length()
}
t.current = nil
currentBasicToken := t.currentBasicToken()
if currentBasicToken != nil {
switch currentBasicToken.getType() {
case leftParenthesis:
curr := CreateLeftParenthesis(t.currentTokenStartIndex)
t.current = &curr
t.nextBasicToken()
case rightParenthesis:
curr := CreateRightParenthesis(t.currentTokenStartIndex)
t.current = &curr
t.nextBasicToken()
case leftSquareBracket:
curr := CreateLeftSquareBracket(t.currentTokenStartIndex)
t.current = &curr
t.nextBasicToken()
case rightSquareBracket:
curr := CreateRightSquareBracket(t.currentTokenStartIndex)
t.current = &curr
t.nextBasicToken()
case comma:
curr := CreateComma(t.currentTokenStartIndex)
t.current = &curr
t.nextBasicToken()
case period:
curr := CreatePeriod(t.currentTokenStartIndex)
t.current = &curr
t.nextBasicToken()
case space, tab, carriageReturn, newLine, carriageReturnNewLine:
ws := readWhitespace(t.basicTokenizer)
var strs []stringable
for _, w := range ws {
strs = append(strs, w)
}
curr := CreateWhitespace(
t.currentTokenStartIndex, getCombinedText(strs...))
t.current = &curr
case doubleQuote:
qs := readQuotedString(t.basicTokenizer)
var strs []stringable
for _, q := range qs {
strs = append(strs, q)
}
curr := CreateQuotedString(
t.currentTokenStartIndex,
getCombinedText(strs...))
t.current = &curr
case singleQuote:
qts := readQuotedTLEString(t.basicTokenizer)
var strs []stringable
for _, q := range qts {
strs = append(strs, q)
}
curr := CreateQuotedString(
t.currentTokenStartIndex,
getCombinedText(strs...))
t.current = &curr
case dash, digits:
ns := readNumber(t.basicTokenizer)
var strs []stringable
for _, n := range ns {
strs = append(strs, n)
}
curr := CreateNumber(
t.currentTokenStartIndex,
getCombinedText(strs...))
t.current = &curr
default:
literalTokens := []*basicToken{currentBasicToken}
t.nextBasicToken()
for t.currentBasicToken() != nil &&
(t.currentBasicToken().getType() == letters ||
t.currentBasicToken().getType() == digits ||
t.currentBasicToken().getType() == underscore) {
literalTokens = append(literalTokens, t.currentBasicToken())
t.nextBasicToken()
}
var ls []stringable
for _, l := range literalTokens {
ls = append(ls, l)
}
curr := CreateLiteral(t.currentTokenStartIndex, getCombinedText(ls...))
t.current = &curr
}
}
return t.current
}
func (t *Tokenizer) Next() bool {
result := t.ReadToken() != nil
t.skipWhitespace()
return result
}
func (t *Tokenizer) skipWhitespace() {
for t.current != nil && t.current.GetType() == Whitespace {
t.Next()
}
}
type TokenType string
const (
LeftSquareBracket TokenType = "LeftSquareBracket"
RightSquareBracket TokenType = "RightSquareBracket"
LeftParenthesis TokenType = "LeftParenthesis"
RightParenthesis TokenType = "RightParenthesis"
QuotedString TokenType = "QuotedString"
Comma TokenType = "Comma"
Whitespace TokenType = "Whitespace"
Literal TokenType = "Literal"
Period TokenType = "Period"
Number TokenType = "Number"
)
func NewToken(tokenType TokenType, startIndex int, stringValue string) Token {
return Token{
typ: tokenType,
span: Span{startIndex: startIndex, length: len(stringValue)},
stringValue: stringValue,
}
}
type Token struct {
typ TokenType
span Span
stringValue string
}
func (t Token) GetType() TokenType {
return t.typ
}
func (t Token) Span() Span {
return t.span
}
func (t Token) Length() int {
return t.span.getLength()
}
func (t Token) StringValue() string {
return t.stringValue
}
func CreateLeftParenthesis(startIndex int) Token {
return NewToken(LeftParenthesis, startIndex, "(")
}
func CreateRightParenthesis(startIndex int) Token {
return NewToken(RightParenthesis, startIndex, ")")
}
func CreateLeftSquareBracket(startIndex int) Token {
return NewToken(LeftSquareBracket, startIndex, "[")
}
func CreateRightSquareBracket(startIndex int) Token {
return NewToken(RightSquareBracket, startIndex, "]")
}
func CreateComma(startIndex int) Token {
return NewToken(Comma, startIndex, ",")
}
func CreatePeriod(startIndex int) Token {
return NewToken(Period, startIndex, ".")
}
func CreateWhitespace(startIndex int, stringValue string) Token {
return NewToken(Whitespace, startIndex, stringValue)
}
func CreateQuotedString(startIndex int, stringValue string) Token {
return NewToken(QuotedString, startIndex, stringValue)
}
func CreateNumber(startIndex int, stringValue string) Token {
return NewToken(Number, startIndex, stringValue)
}
func CreateLiteral(startIndex int, stringValue string) Token {
return NewToken(Literal, startIndex, stringValue)
}
func CreateEmptyLiteral(startIndex int) Token {
return NewToken(Literal, startIndex, "")
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/utils.go | provider/pkg/tle/utils.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
import (
"fmt"
"strings"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
func quote(s string) string {
if s == "" {
return "\"\""
}
if s[0] == '"' && s[len(s)-1] == '"' {
return s
}
if s[0] == '\'' && s[len(s)-1] == '\'' {
return s
}
if strings.ContainsAny(s, "\"") {
return fmt.Sprintf("'%s'", s)
}
return fmt.Sprintf("\"%s\"", s)
}
func isQuoteCharacter(character byte) bool {
return character == '\'' ||
character == '"'
}
type stringable interface {
toString() string
}
/**
* Get the combined text of the provided values.
*/
func getCombinedText(values ...stringable) string {
var result strings.Builder
for _, v := range values {
_, _ = result.WriteString(v.toString())
}
return result.String()
}
// TODO move this back to tokenizer.go
/**
* Handles reading a single-quoted string inside a JSON-encoded TLE string. Handles both JSON string
* escape characters (e.g. \n, \") and escaped single quotes in TLE style (two single quotes together,
* e.g. 'That''s all, folks!')
*/
func readQuotedTLEString(iterator TokenIterator) []*basicToken {
current := iterator.Current()
contract.Assert(current != nil)
contract.Assert(current.getType() == singleQuote)
quotedStringTokens := []*basicToken{current}
iterator.MoveNext()
escaped := false
for iterator.Current() != nil {
current = iterator.Current()
quotedStringTokens = append(quotedStringTokens, current)
if escaped {
escaped = false
} else {
if current.getType() == backslash {
escaped = true
} else if current.getType() == singleQuote {
// If the next token is also a single quote, it's escaped, otherwise it's the
// end of the string.
iterator.MoveNext()
afterCurrent := iterator.Current()
if afterCurrent == nil {
break
}
if afterCurrent.getType() == singleQuote {
escaped = true
continue
} else {
break
}
}
}
iterator.MoveNext()
}
return quotedStringTokens
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/parser_test.go | provider/pkg/tle/parser_test.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseExpression(t *testing.T) {
for _, test := range []struct {
name string
expression string
expected Value
err error
}{
{name: "Literal unquoted",
expression: "hello there",
expected: &StringValue{
token: Token{typ: "QuotedString",
span: Span{startIndex: 0, length: 13},
stringValue: "\"hello there\""}},
},
{name: "Literal double quoted",
expression: "\"hello there\"",
expected: &StringValue{
token: Token{typ: "QuotedString",
span: Span{startIndex: 0, length: 13},
stringValue: "\"hello there\""}},
},
{name: "Literal single quoted",
expression: "'hello there'",
expected: &StringValue{
token: Token{typ: "QuotedString",
span: Span{startIndex: 0, length: 13},
stringValue: "'hello there'"}},
},
{name: "Literal unquoted with internal single quote",
expression: "hello 'there'",
expected: &StringValue{
token: Token{typ: "QuotedString",
span: Span{startIndex: 0, length: 15},
stringValue: "\"hello 'there'\""}},
},
{name: "Literal unquoted with internal double quote",
expression: "hello \"there\"",
expected: &StringValue{
token: Token{typ: "QuotedString",
span: Span{startIndex: 0, length: 15},
stringValue: "'hello \"there\"'"}},
},
{
name: "Simple Function Invocation",
expression: "\"[parameters('dnsPrefix')]\"",
expected: &FunctionCallValue{
NameToken: Token{
typ: "Literal",
span: Span{
startIndex: 1,
length: 10,
},
stringValue: "parameters",
},
LeftParenthesisToken: &Token{
typ: LeftParenthesis,
span: Span{
startIndex: 11,
length: 1,
},
stringValue: "(",
},
ArgumentExpressions: []Value{
&StringValue{
token: Token{
typ: QuotedString,
span: Span{
startIndex: 12,
length: 11,
},
stringValue: "'dnsPrefix'",
},
},
},
RightParenthesisToken: &Token{
typ: RightParenthesis,
span: Span{
startIndex: 23,
length: 1,
},
stringValue: ")",
},
},
},
{
name: "Nested Functions",
expression: "\"[reference(parameters('clusterName')).fqdn]\"",
expected: NewPropertyAccessValue(&FunctionCallValue{
NameToken: Token{
typ: Literal,
span: Span{startIndex: 1, length: 9},
stringValue: "reference",
},
LeftParenthesisToken: &Token{
typ: LeftParenthesis,
span: Span{
startIndex: 10,
length: 1,
},
stringValue: "(",
},
ArgumentExpressions: []Value{
&FunctionCallValue{
NameToken: Token{
typ: Literal,
span: Span{startIndex: 11, length: 10},
stringValue: "parameters",
},
LeftParenthesisToken: &Token{
typ: LeftParenthesis,
span: Span{startIndex: 21, length: 1},
stringValue: "(",
},
ArgumentExpressions: []Value{
&StringValue{
token: Token{
typ: QuotedString,
span: Span{
startIndex: 22,
length: 13,
},
stringValue: "'clusterName'",
},
},
},
RightParenthesisToken: &Token{
typ: RightParenthesis,
span: Span{
startIndex: 35,
length: 1,
},
stringValue: ")",
},
},
},
RightParenthesisToken: &Token{
typ: RightParenthesis,
span: Span{
startIndex: 36,
length: 1,
},
stringValue: ")",
},
},
Token{typ: Period,
span: Span{startIndex: 37, length: 1},
stringValue: "."},
Token{
typ: Literal,
span: Span{startIndex: 38, length: 4},
stringValue: "fqdn",
},
),
},
{
name: "Multiple Arguments",
expression: "\"[resourceId('Microsoft.Network/networkInterfaces','nic1')]\"",
expected: &FunctionCallValue{
NameToken: Token{
typ: "Literal",
span: Span{
startIndex: 1,
length: 10,
},
stringValue: "resourceId",
},
LeftParenthesisToken: &Token{
typ: LeftParenthesis,
span: Span{
startIndex: 11,
length: 1,
},
stringValue: "(",
},
ArgumentExpressions: []Value{
&StringValue{
token: Token{
typ: QuotedString,
span: Span{
startIndex: 12,
length: 37,
},
stringValue: "'Microsoft.Network/networkInterfaces'",
},
},
&StringValue{
token: Token{
typ: QuotedString,
span: Span{
startIndex: 50,
length: 6,
},
stringValue: "'nic1'",
},
},
},
CommaTokens: []*Token{
{
typ: Comma,
span: Span{
startIndex: 49,
length: 1,
},
stringValue: ",",
},
},
RightParenthesisToken: &Token{
typ: RightParenthesis,
span: Span{
startIndex: 56,
length: 1,
},
stringValue: ")",
},
},
},
{
name: "Function Invocation With Array Traversal",
expression: "\"[parameters('dnsPrefix')[0]]\"",
expected: NewArrayAccessValue(
&FunctionCallValue{
NameToken: Token{
typ: Literal,
span: Span{startIndex: 1, length: 10},
stringValue: "parameters",
},
LeftParenthesisToken: &Token{
typ: LeftParenthesis,
span: Span{startIndex: 11, length: 1},
stringValue: "(",
},
ArgumentExpressions: []Value{
&StringValue{
token: Token{
typ: QuotedString,
span: Span{
startIndex: 12,
length: 11,
},
stringValue: "'dnsPrefix'",
},
},
},
RightParenthesisToken: &Token{
typ: RightParenthesis,
span: Span{
startIndex: 23,
length: 1,
},
stringValue: ")",
},
},
Token{
typ: LeftSquareBracket,
span: Span{startIndex: 24, length: 1},
stringValue: "[",
},
NewNumberValue(Token{typ: Number, span: Span{startIndex: 25, length: 1}, stringValue: "0"}),
Token{typ: RightSquareBracket, span: Span{startIndex: 26, length: 1}, stringValue: "]"},
),
},
{
name: "Function Invocation With Array Traversal And Property Access",
expression: "\"[parameters('dns')[0].ttl.value]\"",
expected: NewPropertyAccessValue(
NewPropertyAccessValue(
NewArrayAccessValue(
&FunctionCallValue{
NameToken: Token{
typ: Literal,
span: Span{startIndex: 1, length: 10},
stringValue: "parameters",
},
LeftParenthesisToken: &Token{
typ: LeftParenthesis,
span: Span{startIndex: 11, length: 1},
stringValue: "(",
},
ArgumentExpressions: []Value{
&StringValue{
token: Token{
typ: QuotedString,
span: Span{
startIndex: 12,
length: 5,
},
stringValue: "'dns'",
},
},
},
RightParenthesisToken: &Token{
typ: RightParenthesis,
span: Span{
startIndex: 17,
length: 1,
},
stringValue: ")",
},
},
Token{
typ: LeftSquareBracket,
span: Span{startIndex: 18, length: 1},
stringValue: "[",
},
NewNumberValue(Token{typ: Number, span: Span{startIndex: 19, length: 1}, stringValue: "0"}),
Token{typ: RightSquareBracket, span: Span{startIndex: 20, length: 1}, stringValue: "]"},
),
Token{typ: Period, stringValue: ".", span: Span{startIndex: 21, length: 1}},
Token{typ: Literal, stringValue: "ttl", span: Span{startIndex: 22, length: 3}}),
CreatePeriod(25),
CreateLiteral(26, "value")),
},
} {
t.Run(test.name, func(t *testing.T) {
res, err := Parse(test.expression)
if test.err != nil {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, test.expected, res.Expression, "%#v", res.Expression)
})
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/visitors.go | provider/pkg/tle/visitors.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
// Visitor visits Value types, allowing resolution to their component types
type Visitor interface {
// VisitArrayAccessValue visits an ArrayAccessValue type
VisitArrayAccessValue(*ArrayAccessValue) error
VisitFunctionCallValue(*FunctionCallValue) error
VisitNumberValue(*NumberValue) error
VisitPropertyAccessValue(*PropertyAccessValue) error
VisitStringValue(*StringValue) error
}
type wrappedVisitor struct {
visitArrayAccessValue func(*ArrayAccessValue) error
visitFunctionCallValue func(*FunctionCallValue) error
visitNumberValue func(*NumberValue) error
visitPropertyAccessValue func(*PropertyAccessValue) error
visitStringValue func(*StringValue) error
}
func (w wrappedVisitor) VisitArrayAccessValue(v *ArrayAccessValue) error {
if w.visitArrayAccessValue != nil {
return w.visitArrayAccessValue(v)
}
panic(v)
}
func (w wrappedVisitor) VisitFunctionCallValue(v *FunctionCallValue) error {
if w.visitFunctionCallValue != nil {
return w.visitFunctionCallValue(v)
}
panic(v)
}
func (w wrappedVisitor) VisitNumberValue(v *NumberValue) error {
if w.visitNumberValue != nil {
return w.visitNumberValue(v)
}
panic(v)
}
func (w wrappedVisitor) VisitPropertyAccessValue(v *PropertyAccessValue) error {
if w.visitPropertyAccessValue != nil {
return w.visitPropertyAccessValue(v)
}
panic(v)
}
func (w wrappedVisitor) VisitStringValue(v *StringValue) error {
if w.visitStringValue != nil {
return w.visitStringValue(v)
}
panic(v)
}
// StringValueVisitor creates a new Visitor specifically designed to use with
// string values. Calling any other visit function will cause a panic
func StringValueVisitor(f func(*StringValue) error) Visitor {
return &wrappedVisitor{visitStringValue: f}
}
// NumberValueVisitor creates a new Visitor specifically designed to use with
// number values. Calling any other visit function will cause a panic
func NumberValueVisitor(f func(*NumberValue) error) Visitor {
return &wrappedVisitor{visitNumberValue: f}
}
func FunctionCallValueVisitor(f func(*FunctionCallValue) error) Visitor {
return &wrappedVisitor{visitFunctionCallValue: f}
}
func PropertyAccessValueVisitor(p func(*PropertyAccessValue) error) Visitor {
return &wrappedVisitor{visitPropertyAccessValue: p}
}
func ArrayAccessValueVisitor(p func(*ArrayAccessValue) error) Visitor {
return &wrappedVisitor{visitArrayAccessValue: p}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/tle/value.go | provider/pkg/tle/value.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package tle
import (
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
type Value interface {
Span() *Span
Accept(visitor Visitor) error
}
func NewStringValue(token Token) *StringValue {
contract.Assert(token.GetType() == QuotedString)
return &StringValue{
token: token,
}
}
type StringValue struct {
token Token
}
func (s *StringValue) Accept(visitor Visitor) error {
return visitor.VisitStringValue(s)
}
func (s *StringValue) Token() Token {
return s.token
}
func (s *StringValue) Span() *Span {
return &s.token.span
}
// NewNumberValue creates a new NumberValue
func NewNumberValue(token Token) *NumberValue {
contract.Assert(token.GetType() == Number)
return &NumberValue{token}
}
type NumberValue struct {
token Token
}
func (n *NumberValue) Span() *Span {
return &n.token.span
}
func (n *NumberValue) Token() Token {
return n.token
}
func (n *NumberValue) Accept(v Visitor) error {
return v.VisitNumberValue(n)
}
func NewPropertyAccessValue(source Value, periodToken Token, nameToken Token) *PropertyAccessValue {
return &PropertyAccessValue{
source: source,
periodToken: periodToken,
nameToken: nameToken,
}
}
type PropertyAccessValue struct {
source Value
periodToken Token
nameToken Token
}
func (p *PropertyAccessValue) Source() Value {
return p.source
}
func (p *PropertyAccessValue) PropertyName() string {
return p.nameToken.StringValue()
}
func (p *PropertyAccessValue) Span() *Span {
result := p.source.Span()
return result.union(&p.nameToken.span)
}
func (p *PropertyAccessValue) Accept(v Visitor) error {
return v.VisitPropertyAccessValue(p)
}
func NewArrayAccessValue(
source Value,
leftSquareBracketToken Token,
indexValue Value,
rightSquareBracketToken Token,
) *ArrayAccessValue {
return &ArrayAccessValue{
source: source,
leftSquareBracketToken: leftSquareBracketToken,
indexValue: indexValue,
rightSquareBracketToken: rightSquareBracketToken,
}
}
type ArrayAccessValue struct {
source Value
leftSquareBracketToken Token
indexValue Value
rightSquareBracketToken Token
}
func (a *ArrayAccessValue) Source() Value {
return a.source
}
func (a *ArrayAccessValue) Index() Value {
return a.indexValue
}
func (a *ArrayAccessValue) Span() *Span {
result := a.source.Span()
return union(result, &a.rightSquareBracketToken.span)
}
func (a *ArrayAccessValue) Accept(v Visitor) error {
return v.VisitArrayAccessValue(a)
}
type FunctionCallValue struct {
NamespaceToken *Token
PeriodToken *Token
NameToken Token
LeftParenthesisToken *Token
CommaTokens []*Token
ArgumentExpressions []Value
RightParenthesisToken *Token
}
func (f *FunctionCallValue) Span() *Span {
return union(f.argumentListSpan(), f.fullNameSpan())
}
func (f *FunctionCallValue) Accept(visitor Visitor) error {
return visitor.VisitFunctionCallValue(f)
}
func (f *FunctionCallValue) fullNameSpan() *Span {
u := union(&f.NamespaceToken.span, &f.PeriodToken.span)
result :=
union(u, &f.NameToken.span)
//Should have had at least one of a namespace or a name, therefore span should be non-empty
contract.Assert(result != nil)
// tslint:disable-next-line: no-non-null-assertion // Asserted
return result
}
func (f *FunctionCallValue) argumentListSpan() *Span {
var result *Span
if f.LeftParenthesisToken != nil {
result = &f.LeftParenthesisToken.span
if f.RightParenthesisToken != nil {
result = result.union(&f.RightParenthesisToken.span)
} else if len(f.ArgumentExpressions) > 0 || len(f.CommaTokens) > 0 {
for i := len(f.ArgumentExpressions) - 1; 0 <= i; i-- {
arg := f.ArgumentExpressions[i]
if arg != nil {
span := arg.Span()
result = result.union(span)
break
}
}
if 0 < len(f.CommaTokens) {
result = result.union(&f.CommaTokens[len(f.CommaTokens)-1].span)
}
}
}
return result
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/version/version.go | provider/pkg/version/version.go | // Copyright 2016-2020, Pulumi Corporation.
package version
import "github.com/blang/semver"
// Version is initialized by the Go linker to contain the semver of this build.
var Version string
func GetVersion() semver.Version {
v := Version
if v == "" {
// fallback to a default version e.g. for unit tests (see: PROVIDER_VERSION in Makefile)
v = "3.0.0-alpha.0+dev"
}
return semver.MustParse(v)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/defaultVersion.go | provider/pkg/versioning/defaultVersion.go | package versioning
import (
"cmp"
"fmt"
"io"
"os"
"slices"
"sort"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/collections"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/providerlist"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"gopkg.in/yaml.v3"
)
type ModuleSpec struct {
// Tracking is a single API version from which updates will be included
Tracking *openapi.ApiVersion `yaml:"tracking,omitempty"`
// Additions are specific resource versions to be included. These *must not* overlap with any resources from the tracking version
Additions *map[openapi.ResourceName]openapi.ApiVersion `yaml:"additions,omitempty"`
// Validation warnings for this module
ExclusionErrors []ExclusionError `yaml:"exclusionErrors,omitempty"`
}
type ExclusionError struct {
ModuleName openapi.ModuleName
ResourceName string
Detail string
}
// A Spec describes what versions of what resources should be included in the module.
// It is the input to schema generation.
type Spec map[openapi.ModuleName]ModuleSpec
// BuildSpec calculates a Spec from available API versions and manual curations (config).
func BuildSpec(spec ModuleVersionResources, curations Curations, existingConfig Spec, activeVersionChecker providerlist.ActiveVersionChecker) Spec {
specs := Spec{}
for moduleName, versionResources := range spec {
existing := existingConfig[moduleName]
builder := moduleSpecBuilder{moduleName: moduleName, activeVersionChecker: activeVersionChecker}
specs[moduleName] = builder.buildSpec(versionResources, curations, existing)
}
return specs
}
type CurationViolation struct {
ModuleName openapi.ModuleName
Detail string
}
func ValidateDefaultConfig(config Spec, curations Curations) []CurationViolation {
var violations []CurationViolation
for moduleName, moduleSpec := range util.MapOrdered(config) {
moduleCuration := curations[moduleName]
expectedTracking := moduleCuration.ExpectTracking
if expectedTracking == "" {
expectedTracking = "stable"
}
var actualTracking string
if moduleSpec.Tracking != nil && openapi.IsPreview(string(*moduleSpec.Tracking)) {
actualTracking = "preview"
} else {
actualTracking = "stable"
}
if expectedTracking != actualTracking {
violations = append(violations, CurationViolation{
ModuleName: moduleName,
Detail: fmt.Sprintf("expected tracking %s but found %s", expectedTracking, actualTracking),
})
}
hasAdditions := moduleSpec.Additions != nil && len(*moduleSpec.Additions) > 0
if moduleCuration.ExpectAdditions != hasAdditions && !moduleCuration.Explicit {
var detail string
if moduleCuration.ExpectAdditions {
detail = "expected additions but found none"
} else {
detail = "expected no additions but found some"
}
violations = append(violations, CurationViolation{
ModuleName: moduleName,
Detail: detail,
})
}
}
return violations
}
// ReadSpec parses a spec from a YAML file
func ReadSpec(path string) (Spec, error) {
jsonFile, err := os.Open(path)
if err != nil {
return nil, err
}
defer jsonFile.Close()
byteValue, err := io.ReadAll(jsonFile)
if err != nil {
return nil, err
}
var curatedVersion Spec
err = yaml.Unmarshal(byteValue, &curatedVersion)
return curatedVersion, err
}
func FindInactiveDefaultVersions(defaultVersions openapi.DefaultVersions, activeVersions providerlist.ActiveVersionChecker) map[openapi.ModuleName][]openapi.ApiVersion {
result := map[openapi.ModuleName][]openapi.ApiVersion{}
for moduleName, versions := range defaultVersions {
inactiveVersions := collections.NewOrderableSet[openapi.ApiVersion]()
for _, version := range versions {
if !activeVersions.HasProviderVersion(version.RpNamespace, version.ApiVersion) {
inactiveVersions.Add(version.ApiVersion)
}
}
if inactiveVersions.Count() > 0 {
result[moduleName] = inactiveVersions.SortedValues()
}
}
return result
}
func DefaultVersionsFromConfig(spec ModuleVersionResources, defaultConfig Spec) (openapi.DefaultVersions, error) {
var err error
defaultVersions := openapi.DefaultVersions{}
for moduleName, versionResources := range spec {
definitions := map[openapi.DefinitionName]openapi.DefinitionVersion{}
moduleConfig, ok := defaultConfig[moduleName]
if !ok {
if len(versionResources) > 0 {
var versions []string
for version := range versionResources {
if version != "" {
versions = append(versions, string(version))
}
}
if len(versions) > 0 {
err = multierror.Append(err, fmt.Errorf("no version specified for %s, available versions: %s", moduleName, strings.Join(versions, ", ")))
}
continue
}
}
if moduleConfig.Tracking != nil {
trackingDefinitions := versionResources[*moduleConfig.Tracking]
for definitionName, definition := range util.MapOrdered(trackingDefinitions) {
definitions[definitionName] = definition
}
}
if moduleConfig.Additions != nil {
for definitionName, apiVersion := range *moduleConfig.Additions {
if existingVersion, ok := definitions[definitionName]; ok {
err = multierror.Append(err, fmt.Errorf("duplicate resource %s:%s from %s and %s", moduleName, definitionName, apiVersion, existingVersion))
} else {
versionDefinitions, ok := versionResources[apiVersion]
if !ok {
err = multierror.Append(err, fmt.Errorf("resource %s:%s not found in %s", moduleName, definitionName, apiVersion))
continue
}
versionDefinition, ok := versionDefinitions[definitionName]
if !ok {
err = multierror.Append(err, fmt.Errorf("resource %s:%s not found in %s", moduleName, definitionName, apiVersion))
continue
}
definitions[definitionName] = versionDefinition
}
}
}
defaultVersions[moduleName] = definitions
}
return defaultVersions, multierror.Flatten(err)
}
type moduleSpecBuilder struct {
moduleName openapi.ModuleName
activeVersionChecker providerlist.ActiveVersionChecker
}
func (b moduleSpecBuilder) buildSpec(versions VersionResources, curations Curations, existing ModuleSpec) ModuleSpec {
var additionsPtr *map[string]openapi.ApiVersion
var trackingPtr *openapi.ApiVersion
var exclusionErrors []ExclusionError
moduleCuration := curations[b.moduleName]
latestVersions := b.findLatestVersions(versions, moduleCuration)
if len(latestVersions) == 0 {
return ModuleSpec{}
}
// If multiple versions required, track the latest and include additional resources from previous versions
var trackingResources codegen.StringSet
if existing.Tracking != nil {
trackingPtr = existing.Tracking
trackingResources = codegen.NewStringSet(util.UnsortedKeys(versions[*trackingPtr])...)
} else if !moduleCuration.Explicit {
// Take the latest version as the new tracking version
maxVersion := maxKey(latestVersions)
if maxVersion != nil {
trackingPtr = maxVersion
// Capture all the resources in the version we're tracking ready to find any resources which aren't in this version
trackingResources = codegen.NewStringSet(latestVersions[*trackingPtr]...)
}
}
sortedVersions := util.UnsortedKeys(versions)
openapi.SortApiVersions(sortedVersions)
existingAdditions := map[openapi.ResourceName]openapi.ApiVersion{}
if existing.Additions != nil {
existingAdditions = *existing.Additions
}
additions := map[openapi.ResourceName]openapi.ApiVersion{}
// Loop through every version in order, skipping excluded and private versions
// and overwriting additions from previous versions.
for _, apiVersion := range sortedVersions {
definitions := versions[apiVersion]
if !moduleCuration.Explicit && (trackingPtr == nil || apiVersion == *trackingPtr) {
continue
}
for definitionName, definition := range util.MapOrdered(definitions) {
isExcluded, exclusionErr := moduleCuration.IsExcluded(definitionName, apiVersion)
if exclusionErr != nil {
exclusionErrors = append(exclusionErrors, ExclusionError{
ModuleName: b.moduleName,
ResourceName: definitionName,
Detail: exclusionErr.Error(),
})
}
if isExcluded || openapi.IsPrivate(string(apiVersion)) {
continue
}
if existingVersion, ok := existingAdditions[definitionName]; ok {
additions[definitionName] = existingVersion
continue
}
if !b.activeVersionChecker.HasProviderVersion(definition.RpNamespace, apiVersion) {
// Don't add if not marked as live
continue
}
if !trackingResources.Has(definitionName) {
additions[definitionName] = apiVersion
}
}
}
if len(additions) > 0 {
additionsPtr = &additions
}
return ModuleSpec{
Tracking: trackingPtr,
Additions: additionsPtr,
ExclusionErrors: exclusionErrors,
}
}
// Returns each resource's latest version grouped by version
func (b moduleSpecBuilder) findLatestVersions(versions VersionResources, curations moduleCuration) map[openapi.ApiVersion][]openapi.ResourceName {
latestResourceVersions := b.findLatestResourceVersions(versions, curations)
latestVersions := map[openapi.ApiVersion][]openapi.ResourceName{}
for resourceName, version := range latestResourceVersions {
latestVersions[version] = append(latestVersions[version], resourceName)
}
for _, resourceNames := range latestVersions {
sort.Strings(resourceNames)
}
return latestVersions
}
func (b moduleSpecBuilder) findLatestResourceVersions(versions VersionResources, curations moduleCuration) map[openapi.ResourceName]openapi.ApiVersion {
candidateVersions := b.filterCandidateVersions(versions, curations.Preview)
candidates := filterVersionResources(versions, candidateVersions)
minimalVersionSet := findMinimalVersionSet(candidates)
minimalVersions := filterVersionResources(candidates, minimalVersionSet)
var orderedVersions []openapi.ApiVersion
for apiVersion := range minimalVersions {
orderedVersions = append(orderedVersions, apiVersion)
}
openapi.SortApiVersions(orderedVersions)
latestResourceVersions := map[openapi.ResourceName]openapi.ApiVersion{}
for i := len(orderedVersions) - 1; i >= 0; i-- {
version := orderedVersions[i]
definitions := minimalVersions[version]
for _, definitionName := range util.SortedKeys(definitions) {
// Only add if not already exists
if _, ok := latestResourceVersions[definitionName]; !ok {
latestResourceVersions[definitionName] = version
}
}
}
return latestResourceVersions
}
func filterVersionResources(versions VersionResources, filter *collections.OrderableSet[openapi.ApiVersion]) VersionResources {
filtered := VersionResources{}
for apiVersion, resourceNames := range versions {
if filter.Has(apiVersion) {
filtered[apiVersion] = resourceNames
}
}
return filtered
}
// filterCandidateVersions returns a sorted list of versions which are the best upgrade options,
// removing versions which have now been superseded by a newer or more stable version.
func (b moduleSpecBuilder) filterCandidateVersions(versions VersionResources, previewPolicy string) *collections.OrderableSet[openapi.ApiVersion] {
orderedVersions := util.UnsortedKeys(versions)
openapi.SortApiVersions(orderedVersions)
liveOrderedVersions := []openapi.ApiVersion{}
for _, version := range orderedVersions {
definitions := versions[version]
// Skip versions with no definitions
if len(definitions) == 0 {
continue
}
firstDefinition := definitions[util.SortedKeys(definitions)[0]]
if b.activeVersionChecker.HasProviderVersion(firstDefinition.RpNamespace, version) {
liveOrderedVersions = append(liveOrderedVersions, version)
}
}
// If there are live versions, consider only those.
if len(liveOrderedVersions) > 0 {
orderedVersions = liveOrderedVersions
}
candidateVersions := collections.NewOrderableSet[openapi.ApiVersion]()
hasFutureStableVersion := false
// Start with newest and work backwards
for i := len(orderedVersions) - 1; i >= 0; i-- {
version := orderedVersions[i]
if openapi.IsPrivate(string(version)) {
continue
}
if previewPolicy == PreviewExclude && openapi.IsPreview(string(version)) {
continue
}
if !openapi.IsPreview(string(version)) || previewPolicy == PreviewPrefer {
candidateVersions.Add(version)
hasFutureStableVersion = true
continue
}
if hasFutureStableVersion {
continue
}
// If no more to iterate through, just add
if i == 0 || !b.containsRecentStable(orderedVersions[:i], version) {
candidateVersions.Add(version)
continue
}
isOld, err := isMoreThanOneYearOld(version)
if err != nil {
panic(fmt.Errorf("error checking version age: %s", err))
}
if isOld {
candidateVersions.Add(version)
}
}
return candidateVersions
}
func isMoreThanOneYearOld(version openapi.ApiVersion) (bool, error) {
asTime, err := openapi.ApiVersionToDate(version)
if err != nil {
return false, fmt.Errorf("failed parsing version as date: %s", version)
}
diff := time.Since(asTime)
// Round up to 366 to account for leap years
return diff.Hours() > 24*366, nil
}
func (b moduleSpecBuilder) containsRecentStable(orderedVersions []openapi.ApiVersion, comparisonVersion openapi.ApiVersion) bool {
for i := len(orderedVersions) - 1; i >= 0; i-- {
previousVersion := orderedVersions[i]
// Only looking for recent stable versions
if openapi.IsPreview(string(previousVersion)) {
continue
}
// Check if stable version is also recent
timeDiff, err := timeBetweenVersions(previousVersion, comparisonVersion)
if err != nil {
panic(errors.Wrapf(err, "failed parsing version as date for %s: %s or %s", b.moduleName, comparisonVersion, previousVersion))
}
const maxRecentVersionTimeInHours = 24 * 366
isRecent := timeDiff.Hours() <= maxRecentVersionTimeInHours
return isRecent
}
return false
}
// findMinimalVersionSet returns the minimum set of versions required to produce all resources
func findMinimalVersionSet(versions VersionResources) *collections.OrderableSet[openapi.ApiVersion] {
orderedVersions := util.UnsortedKeys(versions)
openapi.SortApiVersions(orderedVersions)
latestResourceVersions := map[openapi.ResourceName]openapi.ApiVersion{}
for _, version := range orderedVersions {
definitions := versions[version]
for _, definitionName := range util.SortedKeys(definitions) {
latestVersion, hasLatestVersion := latestResourceVersions[definitionName]
// Insert or update if newer
if !hasLatestVersion || openapi.CompareApiVersions(version, latestVersion) > 0 {
latestResourceVersions[definitionName] = version
}
}
}
minimalVersions := collections.NewOrderableSet[openapi.ApiVersion]()
for _, apiVersion := range latestResourceVersions {
minimalVersions.Add(apiVersion)
}
return minimalVersions
}
func timeBetweenVersions(from, to openapi.ApiVersion) (diff time.Duration, err error) {
if len(from) < 10 || len(to) < 10 {
return diff, fmt.Errorf("invalid version string")
}
fromTime, err := time.Parse("2006-01-02", string(from)[:10])
if err != nil {
return diff, err
}
toTime, err := time.Parse("2006-01-02", string(to)[:10])
if err != nil {
return diff, err
}
return toTime.Sub(fromTime), err
}
func maxKey[K cmp.Ordered, V any](m map[K]V) *K {
keys := util.UnsortedKeys(m)
if len(keys) == 0 {
return nil
}
max := slices.Max(keys)
return &max
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/findOlderVersions.go | provider/pkg/versioning/findOlderVersions.go | package versioning
import (
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/collections"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
)
func findOlderVersions(specVersions ModuleVersionResources, defaultVersions openapi.DefaultVersions) openapi.ModuleVersionList {
olderModuleVersions := openapi.ModuleVersionList{}
for moduleName, versions := range specVersions {
olderVersions := collections.NewOrderableSet[openapi.ApiVersion]()
defaultResourceVersions := defaultVersions[moduleName]
minCuratedVersion := findMinDefaultVersion(defaultResourceVersions)
for version := range versions {
if version == "" || version >= minCuratedVersion {
continue
}
olderVersions.Add(version)
}
olderModuleVersions[moduleName] = olderVersions.SortedValues()
}
return olderModuleVersions
}
func findMinDefaultVersion(resourceVersions map[openapi.DefinitionName]openapi.DefinitionVersion) openapi.ApiVersion {
// TODO: Consider using a pointer instead of empty string for when there is no version
minVersion := openapi.ApiVersion("")
for _, version := range resourceVersions {
if minVersion == "" || version.ApiVersion < minVersion {
minVersion = version.ApiVersion
}
}
return minVersion
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/deprecations.go | provider/pkg/versioning/deprecations.go | package versioning
import (
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/collections"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
)
func FindDeprecations(specVersions ModuleVersionResources, defaultVersions openapi.DefaultVersions) openapi.ModuleVersionList {
deprecationCutoff := openapi.ApiVersion("2021-01-01")
olderVersions := findOlderVersions(specVersions, defaultVersions)
for name, versions := range olderVersions {
filteredVersions := []openapi.ApiVersion{}
for _, version := range versions {
if version < deprecationCutoff {
filteredVersions = append(filteredVersions, version)
}
}
olderVersions[name] = filteredVersions
}
return olderVersions
}
func RemoveDeprecations(versions ModuleVersionResources, deprecations openapi.ModuleVersionList) ModuleVersionResources {
filteredSpec := ModuleVersionResources{}
for moduleName, versionResources := range versions {
filteredVersions := VersionResources{}
versionsToRemove := collections.NewOrderableSet[openapi.ApiVersion](deprecations[moduleName]...)
for apiVersion, resourceNames := range versionResources {
if versionsToRemove.Has(apiVersion) {
continue
}
filteredVersions[apiVersion] = resourceNames
}
filteredSpec[moduleName] = filteredVersions
}
return filteredSpec
}
func ReadDeprecations(deprecationPath string) (openapi.ModuleVersionList, error) {
return openapi.ReadModuleVersionList(deprecationPath)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/build_schema.go | provider/pkg/versioning/build_schema.go | package versioning
import (
"path"
"sort"
"github.com/blang/semver"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/gen"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi/paths"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
type ReadSpecsArgs struct {
// Defaults to ./azure-rest-api-specs
SpecsDir string
// e.g. Compute
NamespaceFilter string
// e.g. "2019-09-01" or "2019*"
VersionsFilter string
}
type BuildSchemaArgs struct {
Specs ReadSpecsArgs
RootDir string
ExcludeExplicitVersions bool
OnlyExplicitVersions bool
ExampleLanguages []string
Version string
}
type BuildSchemaReports struct {
PathChangesResult
// ModuleName -> resourceName -> set of paths, to record resources that have conflicting paths.
PathConflicts map[openapi.ModuleName]map[openapi.ResourceName]map[string][]openapi.ApiVersion
AllResourcesByVersion ModuleVersionResources
AllResourceVersionsByResource ModuleResourceVersions
Pending openapi.ModuleVersionList
CurationViolations []CurationViolation
NamingDisambiguations []resources.NameDisambiguation
SkippedPOSTEndpoints map[openapi.ModuleName]map[string]string
ModuleNameErrors []openapi.ModuleNameError
ForceNewTypes []gen.ForceNewType
TypeCaseConflicts gen.CaseConflicts
FlattenedPropertyConflicts map[string]map[string]any
AllEndpoints map[openapi.ModuleName]map[openapi.ResourceName]map[string]*openapi.Endpoint
InactiveDefaultVersions map[openapi.ModuleName][]openapi.ApiVersion
OldApiVersions map[openapi.ModuleName][]openapi.ApiVersion
TokenPaths map[string]string
}
func (r BuildSchemaReports) WriteTo(outputDir string) ([]string, error) {
return gen.EmitFiles(outputDir, gen.FileMap{
"allEndpoints.json": r.AllEndpoints,
"allResourcesByVersion.json": r.AllResourcesByVersion,
"allResourceVersionsByResource.json": r.AllResourceVersionsByResource,
"curationViolations.json": r.CurationViolations,
"flattenedPropertyConflicts.json": r.FlattenedPropertyConflicts,
"forceNewTypes.json": r.ForceNewTypes,
"inactiveDefaultVersions.json": r.InactiveDefaultVersions,
"namingDisambiguations.json": r.NamingDisambiguations,
"pathChanges.json": r.PathChangesResult,
"pathConflicts.json": r.PathConflicts,
"pending.json": r.Pending,
"moduleNameErrors.json": r.ModuleNameErrors,
"skippedPOSTEndpoints.json": r.SkippedPOSTEndpoints,
"typeCaseConflicts.json": r.TypeCaseConflicts,
"oldApiVersions.json": r.OldApiVersions,
"tokenPaths.json": r.TokenPaths,
})
}
type BuildSchemaResult struct {
PackageSpec schema.PackageSpec
Metadata resources.AzureAPIMetadata
Version VersionMetadata
Reports BuildSchemaReports
Modules openapi.AzureModules
}
func BuildSchema(args BuildSchemaArgs) (*BuildSchemaResult, error) {
specsDir := args.Specs.SpecsDir
if specsDir == "" {
specsDir = path.Join(args.RootDir, "azure-rest-api-specs")
}
modules, diagnostics, err := openapi.ReadAzureModules(specsDir, args.Specs.NamespaceFilter, args.Specs.VersionsFilter)
if err != nil {
return nil, err
}
providerVersion, err := semver.Parse(args.Version)
if err != nil {
return nil, err
}
var versionMetadata VersionMetadata
if args.OnlyExplicitVersions {
versionMetadata = VersionMetadata{}
} else {
versionMetadata, err = LoadVersionMetadata(args.RootDir, modules, int(providerVersion.Major))
if err != nil {
return nil, err
}
}
if !args.OnlyExplicitVersions {
modules = openapi.ApplyTransformations(modules, versionMetadata.DefaultVersions, versionMetadata.PreviousDefaultVersions, nil, nil)
}
pathChanges := findPathChanges(modules, versionMetadata.DefaultVersions, versionMetadata.PreviousDefaultVersions, versionMetadata.Config)
if args.ExcludeExplicitVersions {
modules = openapi.SingleVersion(modules)
}
buildSchemaReports := BuildSchemaReports{
NamingDisambiguations: diagnostics.NamingDisambiguations,
SkippedPOSTEndpoints: diagnostics.SkippedPOSTEndpoints,
ModuleNameErrors: diagnostics.ModuleNameErrors,
PathChangesResult: pathChanges,
AllResourcesByVersion: versionMetadata.AllResourcesByVersion,
AllResourceVersionsByResource: versionMetadata.AllResourceVersionsByResource,
Pending: versionMetadata.Pending,
CurationViolations: versionMetadata.CurationViolations,
AllEndpoints: diagnostics.Endpoints,
InactiveDefaultVersions: versionMetadata.InactiveDefaultVersions,
OldApiVersions: versionMetadata.GetOldApiVersionsPerModule(),
}
generationResult, err := gen.PulumiSchema(args.RootDir, modules, versionMetadata, providerVersion, args.OnlyExplicitVersions)
if err != nil {
return &BuildSchemaResult{
PackageSpec: schema.PackageSpec{},
Metadata: resources.AzureAPIMetadata{},
Version: versionMetadata,
Reports: buildSchemaReports,
}, err
}
buildSchemaReports.ForceNewTypes = generationResult.ForceNewTypes
buildSchemaReports.TypeCaseConflicts = generationResult.TypeCaseConflicts
buildSchemaReports.FlattenedPropertyConflicts = generationResult.FlattenedPropertyConflicts
buildSchemaReports.PathConflicts = generationResult.PathConflicts
buildSchemaReports.TokenPaths = generationResult.TokenPaths
pkgSpec := generationResult.Schema
metadata := generationResult.Metadata
examples := generationResult.Examples
if len(args.ExampleLanguages) > 0 {
// Ensure the spec is stamped with a version - Go gen needs it.
pkgSpec.Version = args.Version
err = gen.Examples(args.RootDir, pkgSpec, metadata, examples, args.ExampleLanguages)
if err != nil {
return nil, err
}
// Remove the version again so it doesn't get written to the schema file.
pkgSpec.Version = ""
}
return &BuildSchemaResult{
PackageSpec: *pkgSpec,
Metadata: *metadata,
Version: versionMetadata,
Reports: buildSchemaReports,
Modules: modules,
}, nil
}
type PathChange struct {
CurrentPath string
PreviousPath string
ResourceName string
}
type MissingExpectedResourceVersion struct {
ModuleName openapi.ModuleName
ResourceName string
Version openapi.ApiVersion
IsPrevious bool
}
type PathChangesResult struct {
Changes []PathChange
MissingPreviousDefaultVersions []MissingExpectedResourceVersion
}
func findPathChanges(modules openapi.AzureModules,
defaultVersions openapi.DefaultVersions,
previousDefaultVersions openapi.DefaultVersions,
curations Curations) PathChangesResult {
result := []PathChange{}
missingPreviousDefaultVersions := []MissingExpectedResourceVersion{}
for moduleName, resources := range util.MapOrdered(defaultVersions) {
previousResources, ok := previousDefaultVersions[moduleName]
if !ok {
continue
}
moduleVersions := modules[moduleName]
sortedResourceNames := []string{}
for resourceName := range resources {
sortedResourceNames = append(sortedResourceNames, resourceName)
}
sort.Strings(sortedResourceNames)
for _, resourceName := range sortedResourceNames {
defaultVersion := resources[resourceName].ApiVersion
previousDefault, ok := previousResources[resourceName]
if !ok {
continue
}
cur := moduleVersions[defaultVersion]
prev := moduleVersions[previousDefault.ApiVersion]
spec, ok := cur.Resources[resourceName]
if !ok {
spec, ok = cur.Invokes[resourceName]
}
if !ok {
missingPreviousDefaultVersions = append(missingPreviousDefaultVersions, MissingExpectedResourceVersion{
ModuleName: moduleName,
ResourceName: resourceName,
Version: previousDefault.ApiVersion,
IsPrevious: false,
})
continue
}
prevSpec, ok := prev.Resources[resourceName]
if !ok {
prevSpec, ok = prev.Invokes[resourceName]
}
if !ok {
missingPreviousDefaultVersions = append(missingPreviousDefaultVersions, MissingExpectedResourceVersion{
ModuleName: moduleName,
ResourceName: resourceName,
Version: previousDefault.ApiVersion,
IsPrevious: true,
})
continue
}
path := paths.NormalizePath(spec.Path)
prevPath := paths.NormalizePath(prevSpec.Path)
if path != prevPath {
excluded, err := curations.IsExcluded(moduleName, resourceName, previousDefault.ApiVersion)
if !excluded && err == nil {
result = append(result, PathChange{
CurrentPath: path,
PreviousPath: prevPath,
ResourceName: resourceName,
})
}
}
}
}
return PathChangesResult{
Changes: result,
MissingPreviousDefaultVersions: missingPreviousDefaultVersions,
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/gen_calculateVersionMetadata_test.go | provider/pkg/versioning/gen_calculateVersionMetadata_test.go | package versioning
import (
"testing"
"time"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/providerlist"
"github.com/stretchr/testify/assert"
)
func TestCalculateVersionMetadata(t *testing.T) {
t.Run("empty", func(t *testing.T) {
sources := VersionSources{}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.NotNil(t, result)
})
t.Run("New module tracks latest version", func(t *testing.T) {
sources := VersionSources{
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2019-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
}), result.Spec)
})
t.Run("New module tracks latest of two preview versions", func(t *testing.T) {
sources := VersionSources{
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2019-01-01-preview": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
"2020-01-01-preview": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01-preview")),
},
}), result.Spec)
})
t.Run("New module tracks preview if more than 1 year newer than last stable", func(t *testing.T) {
sources := VersionSources{
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2019-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
"2020-02-01-preview": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-02-01-preview")),
},
}), result.Spec)
})
t.Run("New module tracks older stable if not yet 1 year old", func(t *testing.T) {
today := time.Now().Format("2006-01-02")
elevenMonthsAgo := time.Now().Add(-time.Hour * 24 * 30 * 11).Format("2006-01-02")
olderStable := openapi.ApiVersion(elevenMonthsAgo)
newerPreview := openapi.ApiVersion(today + "-preview")
sources := VersionSources{
AllResourcesByVersion: ModuleVersionResources{
"Module": {
olderStable: {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
newerPreview: {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(olderStable),
},
}), result.Spec)
})
t.Run("New module prefers live version", func(t *testing.T) {
sources := VersionSources{
ProviderList: providerlist.ProviderList{
Providers: []providerlist.Provider{
{
Namespace: "Microsoft.Module",
ResourceTypes: []providerlist.ResourceType{
{
ResourceType: "Resource1",
ApiVersions: []string{"2019-01-01"},
},
{
ResourceType: "Resource2",
ApiVersions: []string{"2019-01-01"},
},
},
},
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2019-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2019-01-01")),
},
}), result.Spec)
})
t.Run("New module with partial latest version includes additions if live", func(t *testing.T) {
sources := VersionSources{
ProviderList: providerlist.ProviderList{
Providers: []providerlist.Provider{
{
Namespace: "Microsoft.Module",
ResourceTypes: []providerlist.ResourceType{
{
ResourceType: "Resource1",
ApiVersions: []string{"2020-01-01", "2021-01-01"},
},
{
ResourceType: "Resource2",
ApiVersions: []string{"2020-01-01"},
},
},
},
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
"2021-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
// Tracks latest
Tracking: ptr(openapi.ApiVersion("2021-01-01")),
// Adds specific resources missing from latest
Additions: &map[string]openapi.ApiVersion{
"Resource2": "2020-01-01",
},
},
}), result.Spec)
})
t.Run("New spec from config excluding all future versions of resource", func(t *testing.T) {
sources := VersionSources{
Config: map[openapi.ModuleName]moduleCuration{
"Module": {
Exclusions: map[openapi.ResourceName]openapi.ApiVersion{
"Resource2": "*",
},
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2019-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
}), result.Spec)
})
t.Run("New spec from config excluding specific recent resource version", func(t *testing.T) {
sources := VersionSources{
Config: map[openapi.ModuleName]moduleCuration{
"Module": {
Exclusions: map[openapi.ResourceName]openapi.ApiVersion{
"Resource2": "2019-01-01",
},
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2019-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
}), result.Spec)
})
t.Run("New spec with preference for explicit version selection", func(t *testing.T) {
sources := VersionSources{
Config: map[openapi.ModuleName]moduleCuration{
"Module": {
Explicit: true,
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2019-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
ProviderList: providerlist.ProviderList{
Providers: []providerlist.Provider{
{
Namespace: "Microsoft.Module",
ResourceTypes: []providerlist.ResourceType{
{
ResourceType: "Resource1",
ApiVersions: []string{"2019-01-01", "2020-01-01"},
},
{
ResourceType: "Resource2",
ApiVersions: []string{"2019-01-01"},
},
},
},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Additions: &map[string]openapi.ApiVersion{
"Resource1": "2020-01-01",
"Resource2": "2019-01-01",
},
},
}), result.Spec)
})
t.Run("New resource ignored if not live", func(t *testing.T) {
sources := VersionSources{
ProviderList: providerlist.ProviderList{
Providers: []providerlist.Provider{
{
Namespace: "Microsoft.Module",
ResourceTypes: []providerlist.ResourceType{
{
ResourceType: "Resource1",
ApiVersions: []string{"2020-01-01"},
},
{
ResourceType: "Resource2",
ApiVersions: []string{"2020-01-01"},
},
},
},
},
},
Spec: map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
"2021-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
}), result.Spec)
})
t.Run("New version ignored if already tracking during upgrade", func(t *testing.T) {
sources := VersionSources{
Spec: map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
"2021-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
}), result.Spec)
})
t.Run("New resource in new version added during upgrade if live", func(t *testing.T) {
sources := VersionSources{
ProviderList: providerlist.ProviderList{
Providers: []providerlist.Provider{
{
Namespace: "Microsoft.Module",
ResourceTypes: []providerlist.ResourceType{
{
ResourceType: "Resource1",
ApiVersions: []string{"2020-01-01", "2021-01-01"},
},
{
ResourceType: "Resource2",
ApiVersions: []string{"2021-01-01"},
},
},
},
},
},
Spec: map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
"2021-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
Additions: &map[string]openapi.ApiVersion{
"Resource2": "2021-01-01",
},
},
}), result.Spec)
})
t.Run("Remove previous addition via exclusion", func(t *testing.T) {
sources := VersionSources{
Spec: map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
Additions: &map[string]openapi.ApiVersion{
"Resource2": "2021-01-01",
},
},
},
Config: map[openapi.ModuleName]moduleCuration{
"Module": {
Exclusions: map[openapi.ResourceName]openapi.ApiVersion{
"Resource2": "2021-01-01",
},
},
},
AllResourcesByVersion: ModuleVersionResources{
"Module": {
"2020-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}},
"2021-01-01": {"Resource1": {
RpNamespace: "Microsoft.Module",
}, "Resource2": {
RpNamespace: "Microsoft.Module",
}},
},
},
}
result, err := calculateVersionMetadata(sources)
assert.NoError(t, err)
assert.Equal(t, Spec(map[openapi.ModuleName]ModuleSpec{
"Module": {
Tracking: ptr(openapi.ApiVersion("2020-01-01")),
},
}), result.Spec)
})
}
func ptr[T any](s T) *T {
return &s
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/gen.go | provider/pkg/versioning/gen.go | package versioning
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"slices"
"strings"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/gen"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi/paths"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/providerlist"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"gopkg.in/yaml.v3"
)
type VersionMetadata struct {
VersionSources
// module->resource->[]version
AllResourceVersionsByResource ModuleResourceVersions
// map[ModuleName][]ApiVersion
Pending openapi.ModuleVersionList
Spec Spec
DefaultVersions openapi.DefaultVersions
CurationViolations []CurationViolation
InactiveDefaultVersions map[openapi.ModuleName][]openapi.ApiVersion
}
// Ensure our VersionMetadata type implements the gen.Versioning interface
// The compiler will raise an error here if the interface isn't implemented
var _ gen.Versioning = (*VersionMetadata)(nil)
// Determine if an explicit resource version is being included in the SDK.
// Version being nil indicates the default version of the resource which should always be included.
func (v VersionMetadata) ShouldInclude(moduleName openapi.ModuleName, version *openapi.ApiVersion, typeName, token string) bool {
// Nil version indicates this is in the default version.
if version == nil {
return true
}
// In v2 only: Keep any default versions as explicit versions too
if v.MajorVersion < 3 && v.DefaultVersions.IsAtVersion(moduleName, typeName, *version) {
return true
}
// Keep any resources in the previous version lock for easier migration
if v.MajorVersion >= 3 && v.PreviousDefaultVersions.IsAtVersion(moduleName, typeName, *version) {
// We're making an exception for these types because we want to remove their previous default version since it
// was broken and had no Pulumi Cloud users according to Metabase. #3817
if moduleName == "MachineLearningServices" && (typeName == "ConnectionRaiBlocklist" || typeName == "ConnectionRaiBlocklistItem") {
return false
}
return true
}
// Exclude versions from removed versions
if versions, ok := v.RemovedVersions[moduleName]; ok {
for _, removedVersion := range versions {
if removedVersion == *version {
return false
}
}
}
// Exclude removed resources
if _, ok := v.ResourcesToRemove[token]; ok {
return false
}
// Exclude removed invokes
if _, ok := v.RemovedInvokes[token]; ok {
return false
}
return true
}
func (v VersionMetadata) GetDeprecation(token string) (gen.ResourceDeprecation, bool) {
if newToken, ok := v.NextResourcesToRemove[token]; ok {
return gen.ResourceDeprecation{
ReplacementToken: newToken,
}, true
}
return gen.ResourceDeprecation{}, false
}
func (v VersionMetadata) GetAllVersions(moduleName openapi.ModuleName, resource openapi.ResourceName) []openapi.ApiVersion {
return v.AllResourceVersionsByResource[moduleName][resource]
}
func (v VersionMetadata) GetPreviousCompatibleTokensLookup() (*gen.CompatibleTokensLookup, error) {
return gen.NewCompatibleTokensLookup(v.PreviousTokenPaths)
}
// Collect, for each module, the API versions that are older than any _previous_ default version and that weren't
// explicitly removed.
func (v VersionMetadata) GetOldApiVersionsPerModule() map[openapi.ModuleName][]openapi.ApiVersion {
result := map[openapi.ModuleName][]openapi.ApiVersion{}
for moduleName, resourceVersions := range v.AllResourceVersionsByResource {
// Collect the explicitly removed versions in a set for easy lookup. We don't want to list them as removable
// when they're already removed.
removedFromModule := map[openapi.ApiVersion]struct{}{}
for _, version := range v.RemovedVersions[moduleName] {
removedFromModule[version] = struct{}{}
}
// API versions can be removed by module, not by resource. Determine the oldest previous default version for
// this module. It's the cut-off below which we can safely remove versions.
previousDefaultVersions := []openapi.ApiVersion{}
for _, version := range v.PreviousDefaultVersions[moduleName] {
previousDefaultVersions = append(previousDefaultVersions, version.ApiVersion)
}
if len(previousDefaultVersions) == 0 {
continue
}
oldestPreviousDefaultVersion := slices.MinFunc(previousDefaultVersions, openapi.CompareApiVersions)
// With oldestPreviousDefaultVersion as cut-off, iterate over all resources and their versions and collect the
// versions that are older than the cut-off.
oldVersionsSet := map[openapi.ApiVersion]struct{}{}
for _, versions := range resourceVersions {
for _, version := range versions {
if _, ok := removedFromModule[version]; !ok && openapi.CompareApiVersions(version, oldestPreviousDefaultVersion) < 0 {
oldVersionsSet[version] = struct{}{}
}
}
}
// If there are any old versions, sort them and add them to the result.
if len(oldVersionsSet) > 0 {
oldVersions := util.UnsortedKeys(oldVersionsSet)
slices.SortStableFunc(oldVersions, openapi.CompareApiVersions)
result[moduleName] = oldVersions
}
}
return result
}
func LoadVersionMetadata(rootDir string, modules openapi.AzureModules, majorVersion int) (VersionMetadata, error) {
versionSources, err := ReadVersionSources(rootDir, modules, majorVersion)
if err != nil {
return VersionMetadata{}, err
}
return calculateVersionMetadata(versionSources)
}
func calculateVersionMetadata(versionSources VersionSources) (VersionMetadata, error) {
indexedProviderList := versionSources.ProviderList.Index()
allResourcesByVersionWithoutDeprecations := RemoveDeprecations(versionSources.AllResourcesByVersion, versionSources.RemovedVersions)
spec := versionSources.Spec
config := versionSources.Config
spec = BuildSpec(allResourcesByVersionWithoutDeprecations, config, spec, indexedProviderList)
violations := ValidateDefaultConfig(spec, config)
v2Lock, err := DefaultVersionsFromConfig(allResourcesByVersionWithoutDeprecations, spec)
if err != nil {
// Format updated spec to YAML and print for context
specYaml, yamlErr := yaml.Marshal(spec)
if yamlErr != nil {
log.Printf("error marshalling spec to YAML: %v", err)
}
wrapped := fmt.Errorf("generating default version lock from spec\n%s\n%w", string(specYaml), err)
return VersionMetadata{}, wrapped
}
inactiveVersions := FindInactiveDefaultVersions(v2Lock, indexedProviderList)
return VersionMetadata{
VersionSources: versionSources,
AllResourceVersionsByResource: FormatResourceVersions(versionSources.AllResourcesByVersion),
Pending: FindNewerVersions(versionSources.AllResourcesByVersion, v2Lock),
Spec: spec,
DefaultVersions: v2Lock,
CurationViolations: violations,
InactiveDefaultVersions: inactiveVersions,
}, nil
}
func (v VersionMetadata) WriteTo(outputDir string) ([]string, error) {
filePrefix := fmt.Sprintf("v%d", v.MajorVersion)
specPath := filePrefix + "-spec.yaml"
lockPath := filePrefix + ".yaml"
return gen.EmitFiles(outputDir, gen.FileMap{
specPath: v.Spec,
lockPath: v.DefaultVersions,
})
}
type VersionSources struct {
MajorVersion int
ProviderList providerlist.ProviderList
requiredExplicitResources []string
// map[ModuleName]map[DefinitionName]ApiVersion
PreviousDefaultVersions openapi.DefaultVersions
RemovedVersions openapi.ModuleVersionList
Spec Spec
Config Curations
ConfigPath string
// Module->version->[]resource
AllResourcesByVersion ModuleVersionResources
// map[TokenToRemove]TokenReplacedWith
ResourcesToRemove ResourceRemovals
RemovedInvokes ResourceRemovals
NextResourcesToRemove ResourceRemovals
// This is not required and will be empty if the file does not exist.
PreviousTokenPaths map[string]string
}
func ReadVersionSources(rootDir string, modules openapi.AzureModules, majorVersion int) (VersionSources, error) {
providerList, err := providerlist.ReadProviderList(filepath.Join(rootDir, "versions", "az-provider-list.json"))
if err != nil {
return VersionSources{}, err
}
knownExplicitResources, err := ReadRequiredExplicitResources(filepath.Join(rootDir, "versions", "required-explicit-resources.txt"))
if err != nil {
return VersionSources{}, err
}
previousPrefix := fmt.Sprintf("v%d", majorVersion-1)
previousLockPath := filepath.Join(rootDir, "versions", previousPrefix+".yaml")
previousLock, err := openapi.ReadDefaultVersions(previousLockPath)
if err != nil {
return VersionSources{}, err
}
filePrefix := fmt.Sprintf("v%d-", majorVersion)
removed, err := ReadDeprecations(filepath.Join(rootDir, "versions", filePrefix+"removed.json"))
if err != nil {
return VersionSources{}, err
}
spec, err := ReadSpec(filepath.Join(rootDir, "versions", filePrefix+"spec.yaml"))
if err != nil {
return VersionSources{}, err
}
configPath := filepath.Join(rootDir, "versions", filePrefix+"config.yaml")
config, err := ReadManualCurations(configPath)
if err != nil {
return VersionSources{}, err
}
resourcesToRemovePath := filepath.Join(rootDir, "versions", filePrefix+"removed-resources.json")
resourcesToRemove, err := ReadResourceRemovals(resourcesToRemovePath)
if err != nil {
return VersionSources{}, fmt.Errorf("could not read %s: %v", resourcesToRemovePath, err)
}
removedInvokesPath := filepath.Join(rootDir, "versions", filePrefix+"removed-invokes.yaml")
removedInvokes, err := ReadResourceRemovals(removedInvokesPath)
if err != nil {
return VersionSources{}, fmt.Errorf("could not read %s: %v", removedInvokesPath, err)
}
nextVersionFilePrefix := fmt.Sprintf("v%d-", majorVersion+1)
nextResourcesToRemovePath := filepath.Join(rootDir, "versions", nextVersionFilePrefix+"removed-resources.json")
nextResourcesToRemove, err := ReadResourceRemovals(nextResourcesToRemovePath)
if err != nil {
return VersionSources{}, fmt.Errorf("could not read %s: %v", nextResourcesToRemovePath, err)
}
previousTokenPathsPath := filepath.Join(rootDir, "versions", previousPrefix+"-token-paths.json")
previousTokenPaths, err := ReadTokenPaths(previousTokenPathsPath)
if err != nil {
return VersionSources{}, fmt.Errorf("could not read %s: %v", previousTokenPathsPath, err)
}
return VersionSources{
MajorVersion: majorVersion,
ProviderList: *providerList,
requiredExplicitResources: knownExplicitResources,
PreviousDefaultVersions: previousLock,
RemovedVersions: removed,
Spec: spec,
Config: config,
ConfigPath: configPath,
AllResourcesByVersion: FindAllResources(modules),
ResourcesToRemove: resourcesToRemove,
RemovedInvokes: removedInvokes,
NextResourcesToRemove: nextResourcesToRemove,
PreviousTokenPaths: previousTokenPaths,
}, nil
}
// ReadRequiredExplicitResources reads a list of resource tokens which map to an equivalent resource which can be migrated to.
type ResourceRemovals map[string]string
func ReadResourceRemovals(path string) (ResourceRemovals, error) {
resourceRemovals, err := ReadSource[ResourceRemovals](path)
if err != nil {
return nil, err
}
return *resourceRemovals, nil
}
func ReadTokenPaths(path string) (map[string]string, error) {
tokenPaths, err := ReadSource[map[string]string](path)
if err != nil {
if os.IsNotExist(err) {
return map[string]string{}, nil
}
return nil, err
}
return *tokenPaths, nil
}
func ReadSource[T any](path string) (*T, error) {
isYaml := filepath.Ext(path) == ".yaml"
sourceFile, err := os.Open(path)
if err != nil {
return nil, err
}
defer sourceFile.Close()
byteValue, err := io.ReadAll(sourceFile)
if err != nil {
return nil, err
}
var result T
if isYaml {
err = yaml.Unmarshal(byteValue, &result)
} else {
err = json.Unmarshal(byteValue, &result)
}
if err != nil {
return nil, err
}
return &result, nil
}
func (s ResourceRemovals) PreserveResources(tokens []string) {
for _, token := range tokens {
_, ok := s[token]
if ok {
delete(s, token)
}
}
}
func ReadRequiredExplicitResources(path string) ([]string, error) {
txtFile, err := os.Open(path)
if err != nil {
return nil, err
}
defer txtFile.Close()
// Read each line into an array
bytes, err := io.ReadAll(txtFile)
if err != nil {
return nil, err
}
// Split on new line
lines := strings.Split(string(bytes), "\r")
return lines, nil
}
func FindRemovedInvokesFromResources(modules openapi.AzureModules, removedResources openapi.RemovableResources) openapi.RemovableResources {
removableInvokes := openapi.RemovableResources{}
for moduleName, versions := range modules {
for version, resources := range versions {
removedResourcePaths := []string{}
for resourceName, resource := range resources.Resources {
if removedResources.CanBeRemoved(moduleName, resourceName, string(version)) {
removedResourcePaths = append(removedResourcePaths, paths.NormalizePath(resource.Path))
continue
}
}
for invokeName, invoke := range resources.Invokes {
fullyQualifiedName := openapi.ToFullyQualifiedName(moduleName, invokeName, string(version))
// Check if the "resource" removal is actually an invoke.
if removedResources.CanBeRemoved(moduleName, invokeName, string(version)) {
removableInvokes[fullyQualifiedName] = ""
continue
}
invokePath := paths.NormalizePath(invoke.Path)
// Try to match on the path - if the invoke sits below a.
found := false
for _, resourcePath := range removedResourcePaths {
if strings.HasPrefix(invokePath, resourcePath) {
found = true
break
}
}
if found {
removableInvokes[fullyQualifiedName] = ""
continue
}
}
}
}
return removableInvokes
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/specs.go | provider/pkg/versioning/specs.go | package versioning
import (
"slices"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
)
type VersionResources = map[openapi.ApiVersion]map[openapi.DefinitionName]openapi.DefinitionVersion
// Module->version->[]resource
type ModuleVersionResources = map[openapi.ModuleName]VersionResources
func FindAllResources(moduleVersions openapi.AzureModules) ModuleVersionResources {
formatted := ModuleVersionResources{}
for moduleName, versions := range moduleVersions {
versionResources := VersionResources{}
for version, resources := range versions {
specResources := map[openapi.DefinitionName]openapi.DefinitionVersion{}
definitions := resources.All()
for definitionName, spec := range util.MapOrdered(definitions) {
specResources[definitionName] = openapi.DefinitionVersion{
ApiVersion: version,
SpecFilePath: spec.FileLocation,
ResourceUri: spec.Path,
RpNamespace: spec.ModuleNaming.RpNamespace,
}
}
if len(specResources) > 0 {
versionResources[version] = specResources
}
}
formatted[moduleName] = versionResources
}
return formatted
}
type ResourceVersions = map[openapi.DefinitionName][]openapi.ApiVersion
type ModuleResourceVersions = map[openapi.ModuleName]ResourceVersions
// FormatResourceVersions flips the hierarchy from Version->Resources to Resource->Versions
func FormatResourceVersions(moduleVersions ModuleVersionResources) ModuleResourceVersions {
formatted := ModuleResourceVersions{}
for moduleName, versions := range moduleVersions {
resourceVersions := ResourceVersions{}
for version, resources := range versions {
for _, definitionName := range util.SortedKeys(resources) {
resourceVersions[definitionName] = append(resourceVersions[definitionName], version)
}
}
for _, apiVersions := range resourceVersions {
slices.Sort(apiVersions)
}
formatted[moduleName] = resourceVersions
}
return formatted
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/manualCuration.go | provider/pkg/versioning/manualCuration.go | package versioning
import (
"fmt"
"io"
"os"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"gopkg.in/yaml.v3"
)
const (
// PreviewExclude means that the preview versions are excluded from consideration for the default version
PreviewExclude = "exclude"
// PreviewPrefer means that the preview versions are preferred over stable versions if newer
PreviewPrefer = "prefer"
)
const (
ExpectTrackingAny = ""
ExpectTrackingStable = "stable"
ExpectTrackingPreview = "preview"
)
const ExclusionAllVersions = "*"
// moduleCuration contains manual edits to the automatically determined API versions for a module
type moduleCuration struct {
// Exclude these resources from the module. Used when generating the final vN.json from vN-config.yaml.
// The value is the API version to exclude, or `*` to exclude all versions.
Exclusions map[openapi.ResourceName]openapi.ApiVersion `yaml:"exclusions,omitempty"`
// Don't use a tracking version, list all resources with their API version instead. Used when generating vN-config.yaml.
Explicit bool `yaml:"explicit"`
// Either "exclude" or "prefer"
Preview string `yaml:"preview"`
// Either "stable" or "preview" - defaults to expecting stable tracking version
ExpectTracking string `yaml:"expectTracking"`
// Whether to expect additions to the module. Defaults to false.
ExpectAdditions bool `yaml:"expectAdditions"`
}
// Curations contains manual edits to the automatically determined API versions
type Curations map[openapi.ModuleName]moduleCuration
// The error is returned when the exclusion is specified but the range doesn't include the requested version
func (curation moduleCuration) IsExcluded(resourceName openapi.ResourceName, apiVersion openapi.ApiVersion) (bool, error) {
if curation.Exclusions == nil {
return false, nil
}
excludedMaxVersion, ok := curation.Exclusions[resourceName]
if !ok {
return false, nil
}
if excludedMaxVersion == ExclusionAllVersions {
return true, nil
}
if openapi.CompareApiVersions(apiVersion, excludedMaxVersion) > 0 {
return false, fmt.Errorf("version %s is greater than %s", apiVersion, excludedMaxVersion)
}
return true, nil
}
// The error is returned when the exclusion is specified but the range doesn't include the requested version
func (c Curations) IsExcluded(moduleName openapi.ModuleName, resourceName openapi.ResourceName, apiVersion openapi.ApiVersion) (bool, error) {
return c[moduleName].IsExcluded(resourceName, apiVersion)
}
func ReadManualCurations(path string) (Curations, error) {
yamlFile, err := os.Open(path)
if err != nil {
return nil, err
}
defer yamlFile.Close()
byteValue, err := io.ReadAll(yamlFile)
if err != nil {
return nil, err
}
var cur Curations
err = yaml.Unmarshal(byteValue, &cur)
return cur, err
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.