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 |
|---|---|---|---|---|---|---|---|---|
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/global.go | src/global.go | package main
import (
"os"
"path/filepath"
"./ui"
"./utils"
)
func installBins(path string) {
var GLOBAL = utils.Path(utils.HOMEDIR(".") + "/.gupm/global")
bins := utils.RecursiveFileWalkDir(GLOBAL + "/.bin")
for _, bin := range bins {
name := filepath.Base(bin)
if !utils.FileExists(path + "/" + name) {
os.Symlink(bin, path+"/"+name)
}
}
}
func GlobalAdd(rls []string) {
ui.Title("Installing global dependency...")
var GLOBAL = utils.Path(utils.HOMEDIR(".") + "/.gupm/global")
if !utils.FileExists(GLOBAL + utils.Path("/gupm.json")) {
os.MkdirAll(GLOBAL, os.ModePerm)
utils.WriteFile(GLOBAL+utils.Path("/gupm.json"), "{}")
}
ui.Log("Installing...")
AddDependency(GLOBAL, rls)
InstallProject(GLOBAL)
ui.Log("Add binaries...")
if utils.OSNAME() != "windows" {
if utils.FileExists("/usr/local/bin/") {
installBins("/usr/local/bin/")
} else {
installBins("/usr/bin/")
}
} else {
ui.Error("Global Installation not supported on Windows yet. Please add .gupm/global/.bin to your PATH")
}
}
func GlobalDelete(rls []string) {
var GLOBAL = utils.Path(utils.HOMEDIR(".") + "/.gupm/global")
if !utils.FileExists(GLOBAL + utils.Path("/gupm.json")) {
os.MkdirAll(GLOBAL, os.ModePerm)
utils.WriteFile(GLOBAL+utils.Path("/gupm.json"), "{}")
}
RemoveDependency(GLOBAL, rls)
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/removeDependency.go | src/removeDependency.go | package main
import (
"./provider"
"./ui"
"./utils"
)
func remove(slice []map[string]interface{}, s int) []map[string]interface{} {
return append(slice[:s], slice[s+1:]...)
}
func RemoveDependency(path string, rls []string) error {
var err error
var packageConfig utils.Json
var depList []map[string]interface{}
ui.Title("Add dependency...")
err = provider.InitProvider(Provider)
if err != nil {
return err
}
providerConfig, err = provider.GetProviderConfig(Provider)
ui.Error(err)
packageConfig, _ = provider.GetPackageConfig(path)
packageConfig, _ = provider.PostGetPackageConfig(packageConfig)
depList, err = provider.GetDependencyList(packageConfig)
if err != nil {
return err
}
ui.Title("Removing from dependency list...")
for _, str := range rls {
for index, dep := range depList {
if dep["name"].(string) == str {
depList = remove(depList, index)
}
}
}
err = provider.SaveDependencyList(path, depList)
if err != nil {
return err
}
// TODO: Remove from module folder
return nil
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/defaultProvider/defaultProvider.go | src/defaultProvider/defaultProvider.go | package defaultProvider
import (
"encoding/json"
"io/ioutil"
"os"
"reflect"
"regexp"
"../ui"
"../utils"
)
func Bootstrap(path string) {
if utils.FileExists(utils.Path(path + "/gupm.json")) {
ui.Error("A project already exists in this folder. Aborting bootstrap.")
return
}
name := ui.WaitForInput("Please enter the name of the project: ")
description := ui.WaitForInput("Enter a description: ")
author := ui.WaitForInput("Enter the author: ")
licence := ui.WaitForInput("Enter the licence (ISC): ")
if name == "" {
ui.Error("Name cannot be empty. Try again")
return
} else {
if licence == "" {
licence = "ISC"
}
fileContent := `{
"name": "` + name + `",
"version": "0.0.1",
"description": "` + description + `",
"author": "` + author + `",
"licence": "` + licence + `"
}`
ioutil.WriteFile(utils.Path(path+"/gupm.json"), []byte(fileContent), os.ModePerm)
}
}
func GetPackageConfig(entryPoint string) map[string]interface{} {
var packageConfig map[string]interface{}
b, err := ioutil.ReadFile(entryPoint)
if err != nil {
ui.Error(err.Error() + " : " + entryPoint)
}
json.Unmarshal([]byte(string(b)), &packageConfig)
return packageConfig
}
func GetDependency(provider string, name string, version string, url string, path string) (string, error) {
return string(utils.HttpGet(url)), nil
}
func PostGetDependency(provider string, name string, version string, url string, path string, result string) (string, error) {
os.MkdirAll(path, os.ModePerm)
tarCheck := regexp.MustCompile(`\.tgz$`)
tryTar := tarCheck.FindString(url)
gzCheck := regexp.MustCompile(`\.gz$`)
trygz := gzCheck.FindString(url)
zipCheck := regexp.MustCompile(`\.zip$`)
tryZip := zipCheck.FindString(url)
if tryTar != "" {
resultFiles, err := utils.Untar(result)
if err != nil {
return path, err
}
resultFiles.SaveAt(path)
} else if trygz != "" {
resultFiles, err := utils.Ungz(result)
if err != nil {
return path, err
}
resultFiles.SaveAt(path)
} else if tryZip != "" {
resultFiles, err := utils.Unzip(result)
if err != nil {
return path, err
}
resultFiles.SaveAt(path)
}
utils.SaveLockDep(path)
return path, nil
}
func GetDependencyList(config map[string]interface{}) []map[string]interface{} {
if config == nil {
ui.Error("no config found. Please bootstrap the project with `g bootstrap`")
return nil
}
depEnv, ok := config["dependencies"].(map[string]interface{})
if !ok {
ui.Log("no dependencies")
return nil
}
depList, hasDefault := depEnv["default"].(map[string]interface{})
if !hasDefault {
ui.Log("no dependencies")
return nil
}
result := make([]map[string]interface{}, 0)
for name, value := range depList {
dep := utils.BuildDependencyFromString("gupm", name)
if reflect.TypeOf(value).String() == "string" {
dep["version"] = value
} else {
valueObject := value.(map[string]interface{})
if valueObject["provider"].(string) != "" {
dep["provider"] = valueObject["provider"]
}
if valueObject["version"].(string) != "" {
dep["version"] = valueObject["version"]
}
}
result = append(result, dep)
}
return result
}
func ExpandDependency(dependency map[string]interface{}) (map[string]interface{}, error) {
configFilePath := utils.Path(dependency["path"].(string) + "/gupm.json")
if utils.FileExists(configFilePath) {
config := GetPackageConfig(configFilePath)
dependency["dependencies"] = make(map[string]interface{})
if config["dependencies"] != nil {
dependency["dependencies"] = GetDependencyList(config)
}
}
return dependency, nil
}
func BinaryInstall(dest string, packagePath string) error {
packages, _ := utils.ReadDir(packagePath)
for _, dep := range packages {
configFilePath := utils.Path(packagePath + "/" + dep.Name() + "/gupm.json")
if utils.FileExists(configFilePath) {
config := GetPackageConfig(configFilePath)
if config["binaries"] != nil {
bins := config["binaries"].(map[string]string)
for name, relPath := range bins {
os.Symlink(utils.Path("/../gupm_modules/"+"/"+dep.Name()+relPath), utils.Path(dest+"/"+name))
}
}
}
}
return nil
}
func SaveDependencyList(path string, depList []map[string]interface{}) error {
config := GetPackageConfig(utils.Path(path + "/gupm.json"))
if config["dependencies"] == nil {
config["dependencies"] = make(map[string]interface{})
}
config["dependencies"].(map[string]interface{})["default"] = make(map[string]interface{})
for _, dep := range depList {
key := utils.BuildStringFromDependency(map[string]interface{}{
"provider": dep["provider"].(string),
"name": dep["name"].(string),
})
config["dependencies"].(map[string]interface{})["default"].(map[string]interface{})[key] = dep["version"].(string)
}
utils.WriteJsonFile(utils.Path(path+"/"+"gupm.json"), config)
return nil
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/defaultProvider/publish.go | src/defaultProvider/publish.go | package defaultProvider
import (
"os"
"../ui"
"../utils"
)
func Publish(path string, namespace string) error {
configPath := utils.Path(path + "/gupm.json")
if utils.FileExists(configPath) {
packageConfig := new(utils.GupmEntryPoint)
errConfig := utils.ReadJSON(configPath, &packageConfig)
if errConfig != nil {
ui.Error("Can't read provider configuration")
return errConfig
}
pname := packageConfig.Name
if namespace != "" {
pname = namespace + "/" + pname
}
ppath := utils.Path(path + "/" + packageConfig.Publish.Dest)
repoConfig := utils.GetOrCreateRepo(ppath)
packageList := repoConfig["packages"].(map[string]interface{})
if packageList[pname] != nil {
if utils.Contains(packageList[pname], packageConfig.Version) {
ui.Error("Package " + pname + "@" + packageConfig.Version + " already published. Please bump the version number.")
return nil
} else {
packageList[pname] = append(utils.ArrString(packageList[pname]), packageConfig.Version)
}
} else {
packageList[pname] = make([]string, 0)
packageList[pname] = append(utils.ArrString(packageList[pname]), packageConfig.Version)
}
installPath := ppath + utils.Path("/"+pname+"/"+packageConfig.Version)
os.MkdirAll(installPath, os.ModePerm)
sourcePaths := make([]string, 0)
for _, src := range packageConfig.Publish.Source {
sourcePaths = append(sourcePaths, utils.Path(path+"/"+src))
}
arch, _ := utils.Tar(sourcePaths)
arch.SaveAt(installPath + utils.Path("/"+packageConfig.Name+"-"+packageConfig.Version+".tgz"))
repoConfig["packages"] = packageList
utils.SaveRepo(ppath, repoConfig)
} else {
ui.Error("Can't find provider configuration")
}
return nil
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/jsVm/jsVm.go | src/jsVm/jsVm.go | package jsVm
import (
"encoding/json"
"errors"
"io/ioutil"
"os"
"path/filepath"
"sync"
"time"
"../ui"
"../utils"
"github.com/Masterminds/semver"
"github.com/robertkrimen/otto"
)
var lock = sync.RWMutex{}
var scriptCache = make(map[string]string)
func Run(path string, input utils.Json) (otto.Value, error) {
var err error
var ret otto.Value
lock.Lock()
if scriptCache[path] == "" {
file, err := ioutil.ReadFile(path)
if err != nil {
return otto.UndefinedValue(), err
}
scriptCache[path] = string(file)
}
script := scriptCache[path]
lock.Unlock()
vm := otto.New()
vm.Interrupt = make(chan func(), 1)
Setup(vm)
vm.Set("_DIRNAME", filepath.Dir(path))
for varName, varValue := range input /*.AsObject()*/ {
vm.Set(varName, varValue)
}
ret, err = vm.Run(script)
if err != nil {
ui.Error(err)
return otto.UndefinedValue(), errors.New("Error occured while executing the GS code")
}
return ret, nil
}
func Setup(vm *otto.Otto) {
vm.Set("httpGetJson", func(call otto.FunctionCall) otto.Value {
url, _ := call.Argument(0).ToString()
res := utils.HttpGet(url)
result, _ := vm.ToValue(utils.StringToJSON(string(res)))
return result
})
vm.Set("httpGet", func(call otto.FunctionCall) otto.Value {
url, _ := call.Argument(0).ToString()
res := utils.HttpGet(url)
result, _ := vm.ToValue(string(res))
return result
})
vm.Set("dir", func(call otto.FunctionCall) otto.Value {
glob, _ := call.Argument(0).ToString()
res, _ := utils.Dir(glob)
result, _ := vm.ToValue(res)
return result
})
vm.Set("osSleep", func(call otto.FunctionCall) otto.Value {
timeMs, _ := call.Argument(0).ToInteger()
time.Sleep(time.Duration(timeMs) * time.Millisecond)
result, _ := vm.ToValue(true)
return result
})
vm.Set("readJsonFile", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
b, err := ioutil.ReadFile(path)
if err != nil {
ui.Error(err)
}
result, _ := vm.ToValue(utils.StringToJSON(string(b)))
return result
})
vm.Set("readFile", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
b, err := ioutil.ReadFile(path)
if err != nil {
ui.Error(err)
}
result, _ := vm.ToValue(string(b))
return result
})
vm.Set("removeFiles", func(call otto.FunctionCall) otto.Value {
files, _ := call.Argument(0).Export()
_, isString := files.(string)
if isString {
files = []string{files.(string)}
}
utils.RemoveFiles(files.([]string))
result, _ := vm.ToValue(true)
return result
})
vm.Set("copyFiles", func(call otto.FunctionCall) otto.Value {
files, _ := call.Argument(0).Export()
_, isString := files.(string)
if isString {
files = []string{files.(string)}
}
path, _ := call.Argument(1).ToString()
path = utils.Path(path)
utils.CopyFiles(files.([]string), path)
result, _ := vm.ToValue(true)
return result
})
vm.Set("pwd", func(call otto.FunctionCall) otto.Value {
dir, _ := os.Getwd()
result, _ := vm.ToValue(dir)
return result
})
vm.Set("env", func(call otto.FunctionCall) otto.Value {
name, _ := call.Argument(0).ToString()
value, _ := call.Argument(1).ToString()
if value == "undefined" {
result, _ := vm.ToValue(os.Getenv(name))
return result
} else {
os.Setenv(name, value)
res, _ := vm.ToValue(true)
return res
}
})
vm.Set("exec", func(call otto.FunctionCall) otto.Value {
exec, _ := call.Argument(0).ToString()
args, _ := call.Argument(1).Export()
_, ok := args.([]string)
if !ok {
args = make([]string, 0)
}
err := utils.ExecCommand(exec, args.([]string))
result, _ := vm.ToValue(err)
return result
})
vm.Set("run", func(call otto.FunctionCall) otto.Value {
exec, _ := call.Argument(0).ToString()
args, _ := call.Argument(1).Export()
_, ok := args.([]string)
if !ok {
args = make([]string, 0)
}
res, err := utils.RunCommand(exec, args.([]string))
if err != nil {
ui.Error(err)
result, _ := vm.ToValue(false)
return result
}
if res != "" {
res = res[:len(res)-1]
}
result, _ := vm.ToValue(res)
return result
})
vm.Set("exit", func(call otto.FunctionCall) otto.Value {
code, _ := call.Argument(0).ToInteger()
os.Exit(int(code))
result, _ := vm.ToValue(true)
return result
})
vm.Set("writeJsonFile", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
toExport, _ := call.Argument(1).Export()
file := JsonExport(toExport).(map[string]interface{})
utils.WriteJsonFile(path, file)
result, _ := vm.ToValue(true)
return result
})
vm.Set("writeFile", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
toExport, _ := call.Argument(1).ToString()
err := ioutil.WriteFile(path, []byte(toExport), os.ModePerm)
if err != nil {
ui.Error(err)
}
result, _ := vm.ToValue(true)
return result
})
vm.Set("_OSNAME", utils.OSNAME())
vm.Set("mkdir", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
os.MkdirAll(path, os.ModePerm)
result, _ := vm.ToValue(true)
return result
})
vm.Set("saveLockDep", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
utils.SaveLockDep(path)
result, _ := vm.ToValue(true)
return result
})
vm.Set("fileExists", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
res := utils.FileExists(path)
result, _ := vm.ToValue(res)
return result
})
vm.Set("waitForInput", func(call otto.FunctionCall) otto.Value {
msg, _ := call.Argument(0).ToString()
res := ui.WaitForInput(msg)
result, _ := vm.ToValue(res)
return result
})
vm.Set("waitForMenu", func(call otto.FunctionCall) otto.Value {
msg, _ := call.Argument(0).Export()
res := ui.WaitForMenu(msg.([]string))
result, _ := vm.ToValue(res)
return result
})
vm.Set("waitForKey", func(call otto.FunctionCall) otto.Value {
ui.WaitForKey()
result, _ := vm.ToValue(true)
return result
})
vm.Set("tar", func(call otto.FunctionCall) otto.Value {
files, _ := call.Argument(0).Export()
_, isString := files.(string)
if isString {
files = []string{files.(string)}
}
res, err := utils.Tar(files.([]string))
if err != nil {
ui.Error(err)
}
b, _ := json.Marshal(res)
result, _ := vm.ToValue(utils.StringToJSON(string(b)))
return result
})
vm.Set("readDir", func(call otto.FunctionCall) otto.Value {
path, _ := call.Argument(0).ToString()
path = utils.Path(path)
var filenames = make([]string, 0)
files, _ := utils.ReadDir(path)
for _, file := range files {
filenames = append(filenames, file.Name())
}
result, _ := vm.ToValue(filenames)
return result
})
vm.Set("createSymLink", func(call otto.FunctionCall) otto.Value {
from, _ := call.Argument(0).ToString()
from = utils.Path(from)
to, _ := call.Argument(1).ToString()
to = utils.Path(to)
err := os.Symlink(from, to)
if err != nil {
ui.Error(err)
}
result, _ := vm.ToValue(true)
return result
})
vm.Set("untar", func(call otto.FunctionCall) otto.Value {
var res utils.FileStructure
file, _ := call.Argument(0).ToString()
res, _ = utils.Untar(file)
b, _ := json.Marshal(res)
result, _ := vm.ToValue(utils.StringToJSON(string(b)))
return result
})
vm.Set("unzip", func(call otto.FunctionCall) otto.Value {
var res utils.FileStructure
file, _ := call.Argument(0).ToString()
res, _ = utils.Unzip(file)
b, _ := json.Marshal(res)
result, _ := vm.ToValue(utils.StringToJSON(string(b)))
return result
})
vm.Set("saveFileAt", func(call otto.FunctionCall) otto.Value {
var fs utils.FileStructure
file, _ := call.Argument(0).Export()
path, _ := call.Argument(1).ToString()
path = utils.Path(path)
bytes, _ := json.Marshal(file)
json.Unmarshal(bytes, &fs)
fs.SaveAt(path)
result, _ := vm.ToValue(path)
return result
})
vm.Set("semverInRange", func(call otto.FunctionCall) otto.Value {
rangeStr, _ := call.Argument(0).ToString()
version, _ := call.Argument(1).ToString()
rangeVer, _ := semver.NewConstraint(rangeStr)
sver, _ := semver.NewVersion(version)
value := rangeVer.Check(sver)
result, _ := vm.ToValue(value)
return result
})
vm.Set("semverLatestInRange", func(call otto.FunctionCall) otto.Value {
rangeStr, _ := call.Argument(0).ToString()
versionListUntyped, _ := call.Argument(1).Export()
versionList := utils.ArrString(versionListUntyped)
var version string
var versionSem *semver.Version
rangeVer, _ := semver.NewConstraint(rangeStr)
for _, verCandUnk := range versionList {
verCand := verCandUnk
sver, err := semver.NewVersion(verCand)
if err != nil {
ui.Error(err)
}
if rangeVer.Check(sver) && (versionSem == nil || sver.GreaterThan(versionSem)) {
version = verCand
versionSem = sver
}
}
if version != "" {
result, _ := vm.ToValue(version)
return result
} else {
return otto.UndefinedValue()
}
})
}
func JsonExport(input interface{}) interface{} {
asMap, isMap := input.(map[string]interface{})
asSlice, isSlice := input.([]interface{})
if isMap {
for index, value := range asMap {
asValue, ok := value.(otto.Value)
if ok {
exported, _ := asValue.Export()
asMap[index] = JsonExport(exported)
}
}
return asMap
} else if isSlice {
for index, value := range asSlice {
asValue, ok := value.(otto.Value)
if ok {
exported, _ := asValue.Export()
asSlice[index] = JsonExport(exported)
}
}
return asSlice
} else {
return input
}
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/utils/json.go | src/utils/json.go | package utils
// import (
// "reflect"
// "fmt"
// )
// type Json map[interface{}]interface {}
type Json map[string]interface{}
// func (j *Json) AsObject() map[string]interface {} {
// res := map[string]interface{}{}
// for i, v := range *j {
// res[i.(string)] = v
// }
// return res
// }
func (j *Json) Contains(test interface{}) bool {
for i := range *j {
if i == test {
return true
}
}
return false
}
func (j *Json) get(index interface{}) interface{} {
return (*j)[index.(string)]
}
// func (j *Json) indexOf(test interface{}) interface{} {
// for i, _ := range *j {
// if(i == test) {
// return true
// }
// }
// return false
// }
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/utils/types.go | src/utils/types.go | package utils
type GupmEntryPoint struct {
Name string
Version string
WrapInstallFolder string
Git gupmEntryPointGit
Publish gupmEntryPointPublish
Cli gupmEntryPointCliList
Config gupmEntryPointConfigList
Dependencies gupmEntryPointDependenciesList
}
type gupmEntryPointCliList struct {
DefaultProviders map[string]string
Aliases map[string]interface{}
}
type gupmEntryPointGit struct {
Hooks gupmEntryPointGitHooks
}
type gupmEntryPointGitHooks struct {
Precommit interface{}
Prepush interface{}
}
type gupmEntryPointDependenciesList struct {
DefaultProvider string
Default map[string]string
}
type gupmEntryPointConfigList struct {
Default gupmEntryPointConfig
}
type gupmEntryPointConfig struct {
Entrypoint string
InstallPath string
DefaultProvider string
OsProviders map[string]string
}
type gupmEntryPointPublish struct {
Source []string
Dest string
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/utils/utils.go | src/utils/utils.go | package utils
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sync"
"time"
"../ui"
"github.com/mitchellh/go-homedir"
)
type Dependency struct {
Name string
Provider string
Version string
}
func buildCmd(toRun string, args []string) *exec.Cmd {
isNode := regexp.MustCompile(`.js$`)
var cmd *exec.Cmd
bashargs := []string{}
// temporary hack to make windows execute js file with node
if isNode.FindString(toRun) != "" {
bashargs = append(bashargs, toRun)
bashargs = append(bashargs, args...)
cmd = exec.Command("node", bashargs...)
} else {
bashargs = append(bashargs, args...)
cmd = exec.Command(toRun, bashargs...)
}
return cmd
}
func ExecCommand(toRun string, args []string) error {
cmd := buildCmd(toRun, args)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err := cmd.Run()
return err
}
func ReadGupmJson(path string) (*GupmEntryPoint, error) {
if !FileExists(path) {
return nil, nil
}
config := new(GupmEntryPoint)
errRead := ReadJSON(path, config)
if errRead != nil {
ui.Error("Can't read", path, "check your file")
return nil, errRead
}
return config, nil
}
func RunCommand(toRun string, args []string) (string, error) {
cmd := buildCmd(toRun, args)
res, err := cmd.Output()
if err != nil {
return "", err
}
return string(res), nil
}
func BuildStringFromDependency(dep map[string]interface{}) string {
rep := dep["name"].(string)
if dep["version"] != nil && dep["version"].(string) != "" {
rep += "@" + dep["version"].(string)
}
if dep["provider"] != nil && dep["provider"].(string) != "" {
rep = dep["provider"].(string) + "://" + rep
}
return rep
}
func BuildDependencyFromString(defaultProvider string, dep string) map[string]interface{} {
result := make(map[string]interface{})
step := dep
versionCheck := regexp.MustCompile(`@[\w\.\-\_\^\~]+$`)
tryversion := versionCheck.FindString(step)
if tryversion != "" {
result["version"] = tryversion[1:]
step = versionCheck.ReplaceAllString(step, "")
} else {
result["version"] = "*.*.*"
}
providerCheck := regexp.MustCompile(`^[\w\-\_]+\:\/\/`)
tryprovider := providerCheck.FindString(step)
if tryprovider != "" {
result["provider"] = tryprovider[:len(tryprovider)-3]
step = providerCheck.ReplaceAllString(step, "")
} else {
result["provider"] = defaultProvider
}
result["name"] = step
return result
}
func StringToJSON(b string) map[string]interface{} {
var jsonString map[string]interface{}
json.Unmarshal([]byte(string(b)), &jsonString)
return jsonString
}
func ReadJSON(path string, target interface{}) error {
b, err := os.Open(path) // just pass the file name
if err != nil {
b.Close()
return err
}
defer b.Close()
return json.NewDecoder(b).Decode(target)
}
var numberConnectionOpened = 0
func HttpGet(url string) []byte {
if numberConnectionOpened > 50 {
time.Sleep(1000 * time.Millisecond)
return HttpGet(url)
}
numberConnectionOpened++
resp, httperr := http.Get(url)
if httperr != nil {
numberConnectionOpened--
isRateLimit, _ := regexp.MatchString(`unexpected EOF$`, httperr.Error())
if !isRateLimit {
ui.Error("Error accessing", url, "trying again.", httperr)
}
time.Sleep(1000 * time.Millisecond)
return HttpGet(url)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
numberConnectionOpened--
ui.Error("Error reading HTTP response ", err)
return HttpGet(url)
}
numberConnectionOpened--
return body
}
func FileExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return true
}
func StringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func RemoveIndex(s []map[string]interface{}, index int) []map[string]interface{} {
return append(s[:index], s[index+1:]...)
}
func RecursiveFileWalkDir(source string) []string {
result := make([]string, 0)
err := filepath.Walk(source,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
result = append(result, path)
}
return nil
})
if err != nil {
ui.Error(err)
}
return result
}
var lock = sync.RWMutex{}
func ReadDir(path string) ([]os.FileInfo, error) {
lock.Lock()
files, err := ioutil.ReadDir(path)
lock.Unlock()
if err != nil {
ui.Error(err)
return files, err
}
return files, nil
}
func IsDirectory(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
return false
}
return fileInfo.IsDir()
}
func HOMEDIR(fallback string) string {
hdir, errH := homedir.Dir()
if errH != nil {
ui.Error(errH)
hdir = fallback
}
return hdir
}
func DIRNAME() string {
ex, err := os.Executable()
exr, err := filepath.EvalSymlinks(ex)
if err != nil {
panic(err)
}
dir := filepath.Dir(exr)
return dir
}
func WriteFile(path string, file string) error {
return ioutil.WriteFile(Path(path), []byte(file), os.ModePerm)
}
func WriteJsonFile(path string, file map[string]interface{}) {
bytes, _ := json.MarshalIndent(file, "", " ")
err := ioutil.WriteFile(path, bytes, os.ModePerm)
if err != nil {
ui.Error(err)
}
}
// TODO: https://blog.golang.org/pipelines
// add proper checksum check
func SaveLockDep(path string) {
ioutil.WriteFile(path+"/.gupm_locked", []byte("1"), os.ModePerm)
}
func AbsPath(rel string) string {
abs, _ := filepath.Abs(rel)
return abs
}
func Path(path string) string {
if runtime.GOOS == "windows" {
return filepath.FromSlash(path)
} else {
return filepath.ToSlash(path)
}
}
func Contains(s interface{}, elem interface{}) bool {
arrV := reflect.ValueOf(s)
if arrV.Kind() == reflect.Slice {
for i := 0; i < arrV.Len(); i++ {
// XXX - panics if slice element points to an unexported struct field
// see https://golang.org/pkg/reflect/#Value.Interface
if arrV.Index(i).Interface() == elem {
return true
}
}
}
return false
}
func ArrString(something interface{}) []string {
_, ok := something.([]string)
if !ok {
res := make([]string, 0)
for _, v := range something.([]interface{}) {
res = append(res, v.(string))
}
return res
} else {
return something.([]string)
}
}
func GupmConfig() gupmEntryPointConfig {
gupmjson, _ := ReadGupmJson(Path(DIRNAME() + "/gupm.json"))
return gupmjson.Config.Default
}
func OSNAME() string {
osName := runtime.GOOS
if osName == "darwin" {
return "mac"
}
return osName
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/utils/untar.go | src/utils/untar.go | package utils
import "archive/tar"
import "archive/zip"
import "compress/gzip"
import (
"bytes"
"io"
"io/ioutil"
"strings"
)
func Ungz(r string) (FileStructure, error) {
tr, err := gzip.NewReader(strings.NewReader(r))
if err != nil {
return EmptyFileStructure, err
}
defer tr.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(tr)
root := FileStructure{
Children: make(map[string]FileStructure),
Name: tr.Header.Name,
Content: buf.Bytes(),
Filetype: 1,
}
return root, nil
}
func Tar(files []string) (FileStructure, error) {
var buf bytes.Buffer
gzw := gzip.NewWriter(&buf)
tw := tar.NewWriter(gzw)
finalList := make([]string, 0)
for _, file := range files {
if IsDirectory(file) {
finalList = append(finalList, RecursiveFileWalkDir(file)...)
} else {
finalList = append(finalList, file)
}
}
for _, file := range finalList {
content, err := ioutil.ReadFile(file)
if err != nil {
return EmptyFileStructure, err
}
hdr := &tar.Header{
Name: file,
Mode: 0740,
Size: int64(len(content)),
}
if err := tw.WriteHeader(hdr); err != nil {
return EmptyFileStructure, err
}
if _, err := tw.Write([]byte(content)); err != nil {
return EmptyFileStructure, err
}
}
if err := tw.Close(); err != nil {
return EmptyFileStructure, err
}
if err := gzw.Close(); err != nil {
return EmptyFileStructure, err
}
root := FileStructure{
Content: buf.Bytes(),
Filetype: 1,
}
return root, nil
}
func Untar(r string) (FileStructure, error) {
gzr, err := gzip.NewReader(strings.NewReader(r))
root := FileStructure{
Children: make(map[string]FileStructure),
Name: "/",
Filetype: 0,
}
if err != nil {
return EmptyFileStructure, err
}
defer gzr.Close()
tr := tar.NewReader(gzr)
for {
header, err := tr.Next()
switch {
case err == io.EOF:
return root, nil
case err != nil:
return root, err
case header == nil:
continue
}
switch header.Typeflag {
// if its a dir and it doesn't exist create it
case tar.TypeDir:
{
root.getOrCreate(header.Name, FileStructure{
Filetype: 0,
})
}
// if it's a file create it
case tar.TypeReg:
buf := new(bytes.Buffer)
buf.ReadFrom(tr)
root.getOrCreate(header.Name, FileStructure{
Filetype: 1,
Content: buf.Bytes(),
})
}
}
return root, nil
}
func Unzip(r string) (FileStructure, error) {
root := FileStructure{
Children: make(map[string]FileStructure),
Name: "/",
Filetype: 0,
}
tr, _ := zip.NewReader(strings.NewReader(r), int64(len(r)))
for _, f := range tr.File {
// if its a dir and it doesn't exist create it
if f.FileInfo().IsDir() {
root.getOrCreate(f.Name, FileStructure{
Filetype: 0,
})
} else {
rc, _ := f.Open()
buf := new(bytes.Buffer)
buf.ReadFrom(rc)
root.getOrCreate(f.Name, FileStructure{
Filetype: 1,
Content: buf.Bytes(),
})
}
}
return root, nil
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/utils/files.go | src/utils/files.go | package utils
import (
"os"
"strings"
// "fmt"
"github.com/bmatcuk/doublestar"
"github.com/otiai10/copy"
)
var EmptyFileStructure = FileStructure{}
type FileStructure struct {
Children map[string]FileStructure
Name string
Content []byte
Filetype int
}
func Dir(path string) (matches []string, err error) {
return doublestar.Glob(path)
}
func RemoveFiles(files []string) error {
for _, file := range files {
return os.RemoveAll(file)
}
return nil
}
func CopyFiles(files []string, destination string) error {
for _, file := range files {
return copy.Copy(file, destination)
}
return nil
}
func (g *FileStructure) getOrCreate(path string, options FileStructure) FileStructure {
var folders = strings.Split(path, "/")
var folder = folders[0]
var child, _ = g.Children[folder]
if child.Name == "" {
if len(folders) > 1 {
g.Children[folder] = FileStructure{
Children: make(map[string]FileStructure),
Name: folder,
Filetype: 0,
}
} else {
g.Children[folder] = FileStructure{
Children: make(map[string]FileStructure),
Name: folder,
Filetype: options.Filetype,
Content: options.Content,
}
}
child, _ = g.Children[folder]
}
if len(folders) > 1 {
next := folders[1:]
return child.getOrCreate(strings.Join(next[:], "/"), options)
} else {
return child
}
}
func (g *FileStructure) SaveSelfAt(path string) error {
if g.Filetype == 0 {
newPath := Path(path + "/" + g.Name)
os.MkdirAll(newPath, os.ModePerm)
for _, child := range g.Children {
child.SaveSelfAt(newPath)
}
} else {
filePath := path
if g.Name != "" {
filePath = Path(filePath + "/" + g.Name)
}
f, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, os.FileMode(0777))
if err != nil {
f.Close()
return err
}
if _, err := f.Write(g.Content); err != nil {
f.Close()
return err
}
f.Close()
}
return nil
}
func (g *FileStructure) SaveAt(path string) error {
if g.Filetype == 0 {
os.MkdirAll(Path(path), os.ModePerm)
for _, child := range g.Children {
child.SaveSelfAt(Path(path))
}
}
if g.Filetype == 1 {
g.SaveSelfAt(Path(path))
}
return nil
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/utils/repo.go | src/utils/repo.go | package utils
import (
"io/ioutil"
)
func GetOrCreateRepo(path string) map[string]interface{} {
configPath := path + "/gupm_repo.json"
if !FileExists(configPath) {
baseConfig := `{
"packages": {}
}`
WriteFile(configPath, baseConfig)
return StringToJSON(baseConfig)
}
file, _ := ioutil.ReadFile(configPath)
return StringToJSON(string(file))
}
func SaveRepo(path string, file map[string]interface{}) {
WriteJsonFile(path+"/gupm_repo.json", file)
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/provider/dependencyTree.go | src/provider/dependencyTree.go | package provider
func eliminateRedundancy(tree []map[string]interface{}, path map[string]bool) []map[string]interface{} {
var cleanTree = make([]map[string]interface{}, 0)
for index, dep := range tree {
if dep["name"] != nil {
_ = index
depKey := dep["name"].(string) + "@" + dep["version"].(string)
if path[depKey] != true {
cleanTree = append(cleanTree, dep)
}
}
}
for index, dep := range cleanTree {
if dep["name"] != nil {
nextDepList, ok := dep["dependencies"].([]map[string]interface{})
if ok {
depKey := dep["name"].(string) + "@" + dep["version"].(string)
newPath := make(map[string]bool)
for key, value := range path {
newPath[key] = value
}
newPath[depKey] = true
newSubTree := eliminateRedundancy(nextDepList, newPath)
cleanTree[index]["dependencies"] = newSubTree
}
}
}
return cleanTree
}
func flattenDependencyTree(tree []map[string]interface{}, subTree []map[string]interface{}) ([]map[string]interface{}, []map[string]interface{}) {
var cleanTree = make([]map[string]interface{}, 0)
for index, dep := range subTree {
var rootDeps = make(map[string]string)
for _, dep := range tree {
rootDeps[dep["name"].(string)] = dep["version"].(string)
}
if rootDeps[dep["name"].(string)] == "" {
tree = append(tree, dep)
nextDepList, ok := dep["dependencies"].([]map[string]interface{})
if ok {
newTree, newSubTree := flattenDependencyTree(tree, nextDepList)
tree = newTree
subTree[index]["dependencies"] = newSubTree
}
} else if rootDeps[dep["name"].(string)] != dep["version"].(string) {
nextDepList, ok := dep["dependencies"].([]map[string]interface{})
if ok {
newTree, newSubTree := flattenDependencyTree(tree, nextDepList)
tree = newTree
subTree[index]["dependencies"] = newSubTree
}
cleanTree = append(cleanTree, subTree[index])
}
}
return tree, cleanTree
}
func BuildDependencyTree(tree []map[string]interface{}) []map[string]interface{} {
cleanTree := eliminateRedundancy(tree, make(map[string]bool))
for index, dep := range cleanTree {
nextDepList, ok := dep["dependencies"].([]map[string]interface{})
if ok {
newCleanTree, newDepList := flattenDependencyTree(cleanTree, nextDepList)
cleanTree = newCleanTree
cleanTree[index]["dependencies"] = newDepList
}
}
return cleanTree
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/provider/install.go | src/provider/install.go | package provider
import (
"io/ioutil"
"os"
"regexp"
"../defaultProvider"
"../jsVm"
"../ui"
"../utils"
)
func BinaryInstall(path string, paths map[string]string) error {
dest := utils.Path(path + "/.bin")
os.RemoveAll(dest)
os.MkdirAll(dest, os.ModePerm)
for pr, prdir := range paths {
depProviderPath := GetProviderPath(pr)
var file = utils.FileExists(depProviderPath + utils.Path("/binaryInstall.gs"))
if pr != "gupm" && file {
input := make(map[string]interface{})
input["Destination"] = dest
input["Source"] = prdir
res, err := jsVm.Run(depProviderPath+utils.Path("/binaryInstall.gs"), input)
if err != nil {
return err
}
_, err1 := res.ToString()
return err1
} else {
return defaultProvider.BinaryInstall(dest, prdir)
}
}
return nil
}
func installDependencySubFolders(path string, depPath string) {
files, _ := utils.ReadDir(path)
for _, file := range files {
if file.IsDir() {
folderPath := utils.Path(depPath + "/" + file.Name())
os.MkdirAll(folderPath, os.ModePerm)
installDependencySubFolders(utils.Path(path+"/"+file.Name()), folderPath)
} else {
isFileExists := false
err := os.Link(utils.Path(path+"/"+file.Name()), utils.Path(depPath+"/"+file.Name()))
if err != nil {
isFileExists, _ = regexp.MatchString(`file exists$`, err.Error())
}
if err != nil && !isFileExists {
if !linkHasErrored {
ui.Error(err)
ui.Error("Error, cannot use hard link on your system. Falling back to copying file (Will be slower!)")
linkHasErrored = true
}
input, err := ioutil.ReadFile(utils.Path(path + "/" + file.Name()))
if err != nil {
ui.Error(err)
return
}
err = ioutil.WriteFile(utils.Path(depPath+"/"+file.Name()), input, 0644)
if err != nil {
ui.Error(err)
return
}
}
}
}
}
func InstallDependency(path string, dep map[string]interface{}) {
depPath := utils.Path(path + "/" + dep["name"].(string))
// if(utils.FileExists(depPath)) {
// // TODO: check version
// } else {
// }
_, ok := dep["path"].(string)
if ok {
os.MkdirAll(utils.Path(depPath), os.ModePerm)
installDependencySubFolders(utils.Path(dep["path"].(string)), depPath)
} else {
ui.Error(dep["name"].(string) + " Cannot be installed.")
}
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/provider/publish.go | src/provider/publish.go | package provider
import (
"errors"
"../defaultProvider"
"../jsVm"
"../utils"
// "fmt"
)
func Publish(path string, namespace string) error {
if Provider != "gupm" {
var file = utils.FileExists(utils.Path(ProviderPath + "/publish.gs"))
if file {
input := make(map[string]interface{})
input["Path"] = path
_, err := jsVm.Run(utils.Path(ProviderPath+"/publish.gs"), input)
return err
} else {
return errors.New("Provider doesn't have any publish function. Please use 'g publish' to use the default publish.")
}
} else {
return defaultProvider.Publish(path, namespace)
}
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/provider/bootstrap.go | src/provider/bootstrap.go | package provider
import (
"../defaultProvider"
"../jsVm"
"../utils"
"errors"
// "fmt"
)
func Bootstrap(path string) error {
if Provider != "gupm" {
var file = utils.FileExists(utils.Path(ProviderPath + "/bootstrap.gs"))
if file {
input := make(map[string]interface{})
input["Path"] = path
_, err := jsVm.Run(utils.Path(ProviderPath+"/bootstrap.gs"), input)
if err != nil {
return err
}
} else {
return errors.New("Provider doesn't have any bootstrap function. Please use 'g bootstrap' to use the default bootstrap.")
}
} else {
defaultProvider.Bootstrap(path)
}
return nil
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/provider/provider.go | src/provider/provider.go | package provider
import (
"fmt"
"os"
"path/filepath"
"sync"
"../defaultProvider"
"../jsVm"
"../ui"
"../utils"
)
var Provider string
var ProviderPath string
var providerConfigCache = make(map[string]*utils.GupmEntryPoint)
var linkHasErrored = false
var pConfigLock = sync.RWMutex{}
func GetProviderPath(name string) string {
gupmConfig := utils.GupmConfig()
if name == "" {
name = gupmConfig.DefaultProvider
}
if name == "os" {
osName := utils.OSNAME()
if gupmConfig.OsProviders[osName] != "" {
name = gupmConfig.OsProviders[osName]
} else {
ui.Error("No provider set for", osName)
return utils.DIRNAME()
}
}
if name == "gupm" {
return utils.DIRNAME()
} else {
homePlugin := utils.HOMEDIR(".") + utils.Path("/.gupm/plugins/provider-"+name)
localPlugin := utils.DIRNAME() + utils.Path("/plugins/provider-"+name)
if utils.FileExists(homePlugin) {
pluginPath, err := filepath.EvalSymlinks(homePlugin)
if err != nil {
ui.Error(err)
return ""
}
return pluginPath
} else if utils.FileExists(localPlugin) {
return localPlugin
} else {
fmt.Println("Provider cannot be found: " + name + ". Please install it before using it.")
os.Exit(1)
return ""
}
}
}
func InitProvider(provider string) error {
Provider = provider
ProviderPath = GetProviderPath(provider)
if Provider != "" {
providerConfig, err := GetProviderConfig(Provider)
if err != nil {
return err
}
ui.Log("Initialisation OK for " + providerConfig.Name)
} else {
providerConfig, err := GetProviderConfig("gupm")
if err != nil {
return err
}
ui.Log("Initialisation OK for " + providerConfig.Name)
}
return nil
}
func GetProviderConfig(providerName string) (*utils.GupmEntryPoint, error) {
providerConfigPath := GetProviderPath(providerName) + utils.Path("/gupm.json")
pConfigLock.Lock()
if providerConfigCache[providerName] == nil {
config, err := utils.ReadGupmJson(providerConfigPath)
if err != nil {
return nil, err
}
providerConfigCache[providerName] = config
pConfigLock.Unlock()
return config, nil
} else {
config := providerConfigCache[providerName]
pConfigLock.Unlock()
return config, nil
}
}
func GetPackageConfig(path string) (utils.Json, error) {
var file = utils.FileExists(ProviderPath + utils.Path("/getPackageConfig.gs"))
if file {
input := make(map[string]interface{})
input["Path"] = path
res, err := jsVm.Run(ProviderPath+utils.Path("/getPackageConfig.gs"), input)
if err != nil {
return nil, err
}
resObj, err1 := res.Export()
return resObj.(utils.Json), err1
} else {
pc, err := GetProviderConfig(Provider)
if err != nil {
return nil, err
}
return defaultProvider.GetPackageConfig(utils.Path(path + "/" + pc.Config.Default.Entrypoint)), nil
}
}
func PostGetPackageConfig(config utils.Json) (utils.Json, error) {
var file = utils.FileExists(ProviderPath + utils.Path("/postGetPackageConfig.gs"))
if file {
input := make(map[string]interface{})
input["PackageConfig"] = config
res, err := jsVm.Run(ProviderPath+utils.Path("/postGetPackageConfig.gs"), input)
if err != nil {
return nil, err
}
resObj, err1 := res.Export()
return resObj.(utils.Json), err1
} else {
return config, nil
}
}
func SaveDependencyList(path string, depList []map[string]interface{}) error {
var file = utils.FileExists(ProviderPath + utils.Path("/saveDependencyList.gs"))
if file {
input := make(map[string]interface{})
input["Dependencies"] = depList
input["Path"] = path
_, err := jsVm.Run(ProviderPath+utils.Path("/saveDependencyList.gs"), input)
if err != nil {
return err
}
return nil
} else {
return defaultProvider.SaveDependencyList(path, depList)
}
}
func GetDependencyList(config utils.Json) ([]map[string]interface{}, error) {
var file = utils.FileExists(ProviderPath + utils.Path("/getDependencyList.gs"))
if file {
input := make(map[string]interface{})
input["PackageConfig"] = config
res, err := jsVm.Run(ProviderPath+utils.Path("/getDependencyList.gs"), input)
if err != nil {
return nil, err
}
resObj, err1 := res.Export()
resMap, ok := resObj.([]map[string]interface{})
if ok {
return resMap, err1
} else {
return make([]map[string]interface{}, 0), err1
}
} else {
return defaultProvider.GetDependencyList(config), nil
}
}
func ResolveDependencyLocation(dependency map[string]interface{}) (map[string]interface{}, error) {
depProviderPath := GetProviderPath(dependency["provider"].(string))
var file = utils.FileExists(depProviderPath + utils.Path("/resolveDependencyLocation.gs"))
if dependency["provider"].(string) != "gupm" && file {
input := make(map[string]interface{})
input["Dependency"] = dependency
res, err := jsVm.Run(depProviderPath+utils.Path("/resolveDependencyLocation.gs"), input)
if err != nil {
return nil, err
}
resObj, err1 := res.Export()
if resObj == nil {
ui.Error("ERROR Failed to resolve" + dependency["name"].(string) + "Trying again.")
return ResolveDependencyLocation(dependency)
}
return resObj.(map[string]interface{}), err1
} else {
dependency["url"] = dependency["name"].(string)
return dependency, nil
}
}
func ExpandDependency(dependency map[string]interface{}) (map[string]interface{}, error) {
depProviderPath := GetProviderPath(dependency["provider"].(string))
var file = utils.FileExists(depProviderPath + utils.Path("/expandDependency.gs"))
if dependency["provider"].(string) != "gupm" && file {
input := make(map[string]interface{})
input["Dependency"] = dependency
res, err := jsVm.Run(depProviderPath+utils.Path("/expandDependency.gs"), input)
if err != nil {
return nil, err
}
toExport, _ := res.Export()
resObj := jsVm.JsonExport(toExport).(map[string]interface{})
if resObj == nil {
ui.Error("ERROR Failed to resolve" + dependency["name"].(string) + ". Trying again.")
return ExpandDependency(dependency)
}
return resObj, nil
} else {
return defaultProvider.ExpandDependency(dependency)
}
}
func GetDependency(provider string, name string, version string, url string, path string) (string, error) {
depProviderPath := GetProviderPath(provider)
var file = utils.FileExists(depProviderPath + utils.Path("/getDependency.gs"))
if provider != "gupm" && file {
input := make(map[string]interface{})
input["Provider"] = provider
input["Name"] = name
input["Version"] = version
input["Url"] = url
input["Path"] = path
res, err := jsVm.Run(depProviderPath+utils.Path("/getDependency.gs"), input)
if err != nil {
return "", err
}
resStr, err1 := res.ToString()
return resStr, err1
} else {
return defaultProvider.GetDependency(provider, name, version, url, path)
}
}
func PostGetDependency(provider string, name string, version string, url string, path string, result string) (string, error) {
depProviderPath := GetProviderPath(provider)
var file = utils.FileExists(depProviderPath + utils.Path("/postGetDependency.gs"))
if provider != "gupm" && file {
input := make(map[string]interface{})
input["Provider"] = provider
input["Name"] = name
input["Version"] = version
input["Url"] = url
input["Path"] = path
input["Result"] = result
res, err := jsVm.Run(depProviderPath+utils.Path("/postGetDependency.gs"), input)
if err != nil {
return "", err
}
resStr, err1 := res.ToString()
return resStr, err1
} else {
return defaultProvider.PostGetDependency(provider, name, version, url, path, result)
}
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/windows/windows_install.go | src/windows/windows_install.go | package main
import (
"../ui"
"../utils"
"fmt"
)
func main() {
arch := utils.HttpGet("https://azukaar.github.io/GuPM/gupm_windows.tar.gz")
files, _ := utils.Untar(string(arch))
path := ui.WaitForInput("Where do you want to save GuPM? (default C:\\)")
if path == "" {
path = "C:\\"
}
files.SaveAt(path)
fmt.Println("GuPM saved in " + path + ". dont forget to add it to your PATH")
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
azukaar/GuPM | https://github.com/azukaar/GuPM/blob/53371f326bf98dc67536562adc10c3e206b41ad6/src/ui/log.go | src/ui/log.go | package ui
import (
"bufio"
"errors"
"fmt"
"github.com/fatih/color"
"github.com/gosuri/uilive"
"os"
"strconv"
"sync"
"time"
)
var errorList = make([]string, 0)
var debugList = make([]string, 0)
var currentLog string
var currentTitle string
var progress int
var screenWidth int
var positionToDrawAt int
var logBox = uilive.New()
var lock = sync.RWMutex{}
var errorLock = sync.RWMutex{}
var redrawNeeded = false
var running = true
var isWaitingForInput = false
func Title(log string) {
_ = color.Green
currentTitle = log
currentLog = ""
redrawNeeded = true
}
func Log(log string) {
currentLog = log
redrawNeeded = true
}
func Error(errs ...interface{}) error {
res := ""
for _, err := range errs {
errErr, isErr := err.(error)
errStr, isStr := err.(string)
if isErr && errErr != nil {
res += " " + errErr.Error()
} else if isStr {
res += " " + errStr
}
}
if res != "" {
errorLock.Lock()
errorList = append(errorList, res)
errorLock.Unlock()
if len(errorList) <= 10 {
redrawNeeded = true
}
return errors.New(res)
} else {
return nil
}
}
func Debug(err string) {
debugList = append(debugList, err)
if len(debugList) <= 10 {
Draw()
}
}
func Progress(p int) {
progress = p
redrawNeeded = true
}
// https://github.com/ahmetb/go-cursor/blob/master/cursor.go
var Esc = "\x1b"
func escape(format string, args ...interface{}) string {
return fmt.Sprintf("%s%s", Esc, fmt.Sprintf(format, args...))
}
func moveCursor(x int, y int) {
escape("[%d;%dH", x, y)
}
func init() {
positionToDrawAt = 0
logBox.Start()
go (func() {
for range time.Tick(200 * time.Millisecond) {
if running {
Draw()
}
}
})()
}
func drawTitle() string {
if currentTitle != "" {
title := color.New(color.FgBlue, color.Bold)
return title.Sprintln("🐶 " + currentTitle)
} else {
return ""
}
}
func drawLog() string {
if currentLog != "" {
log := color.New(color.FgGreen)
return log.Sprintln("✓ " + currentLog)
} else {
return ""
}
}
func Stop() {
redrawNeeded = true
running = false
Draw()
}
func WaitForKey() {
isWaitingForInput = true
logBox.Flush()
reader := bufio.NewReader(os.Stdin)
reader.ReadRune()
isWaitingForInput = false
}
func WaitForInput(msg string) string {
isWaitingForInput = true
logBox.Flush()
fmt.Printf(msg)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
var result = scanner.Text()
isWaitingForInput = false
return result
}
if scanner.Err() != nil {
}
return ""
}
func WaitForMenu(msgs []string) int {
lgth := len(msgs)
i := 1
res := 0
for _, msg := range msgs {
fmt.Println(strconv.Itoa(i) + " : " + msg)
i++
}
for res <= 0 || res > lgth {
resString := WaitForInput("Please input choice 1 - " + strconv.Itoa(lgth) + ": ")
res, _ = strconv.Atoi(resString)
}
return res
}
func Draw() {
if !redrawNeeded || isWaitingForInput {
return
}
result := ""
result += drawTitle()
if progress > 0 {
fmt.Print("📦📦")
for i := 0; i < 20; i++ {
if i == progress/5 {
fmt.Print("🐕")
} else {
fmt.Print("-")
}
}
fmt.Println("🏠")
}
result += drawLog()
errorColor := color.New(color.FgRed)
limit := 0
errorLock.RLock()
for _, v := range errorList {
_ = v
if limit == 10 {
result += errorColor.Sprintln("❌❌❌ Too many errors to display...")
limit++
} else if limit < 10 {
result += errorColor.Sprintln("❌ " + v)
limit++
}
}
errorLock.RUnlock()
limit = 0
for _, v := range debugList {
_ = v
if limit == 10 {
result += "Too many debugs..."
limit++
} else if limit < 10 {
result += v
limit++
}
}
lock.Lock()
if running {
fmt.Fprintf(logBox, result)
} else {
fmt.Fprintf(logBox, "\n")
logBox.Stop()
fmt.Println(result)
}
redrawNeeded = false
lock.Unlock()
}
| go | ISC | 53371f326bf98dc67536562adc10c3e206b41ad6 | 2026-01-07T09:43:21.197412Z | false |
GoogleCloudPlatform/gcp-service-broker | https://github.com/GoogleCloudPlatform/gcp-service-broker/blob/2f676b434e3f9d570f3b1d831f81e3a3de8c7664/main.go | main.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 main
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/cmd"
)
func main() {
cmd.Execute()
}
| 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/validation/constraint_builder.go | pkg/validation/constraint_builder.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 validation
const (
KeyDefault = "default"
KeyExamples = "examples"
KeyDescription = "description"
KeyTitle = "title"
KeyType = "type"
KeyConst = "const"
KeyEnum = "enum"
KeyMultipleOf = "multipleOf"
KeyMaximum = "maximum"
KeyMinimum = "minimum"
KeyExclusiveMaximum = "exclusiveMaximum"
KeyExclusiveMinimum = "exclusiveMinimum"
KeyMaxLength = "maxLength"
KeyMinLength = "minLength"
KeyPattern = "pattern"
KeyMaxItems = "maxItems"
KeyMinItems = "minItems"
KeyMaxProperties = "maxProperties"
KeyMinProperties = "minProperties"
KeyRequired = "required"
KeyPropertyNames = "propertyNames"
)
// NewConstraintBuilder creates a builder for JSON Schema compliant constraint
// lists. See http://json-schema.org/latest/json-schema-validation.html
// for types of validation available.
func NewConstraintBuilder() ConstraintBuilder {
return ConstraintBuilder{}
}
// A builder for JSON Schema compliant constraint lists
type ConstraintBuilder map[string]interface{}
// Type adds a type constrinat.
func (cb ConstraintBuilder) Type(t string) ConstraintBuilder {
cb[KeyType] = t
return cb
}
// Description adds a human-readable description
func (cb ConstraintBuilder) Description(desc string) ConstraintBuilder {
cb[KeyDescription] = desc
return cb
}
// Title adds a human-readable label suitable for labeling a UI element.
func (cb ConstraintBuilder) Title(title string) ConstraintBuilder {
cb[KeyTitle] = title
return cb
}
// Examples adds one or more examples
func (cb ConstraintBuilder) Examples(ex ...interface{}) ConstraintBuilder {
cb[KeyExamples] = ex
return cb
}
// Const adds a constraint that the field must equal this value.
func (cb ConstraintBuilder) Const(value interface{}) ConstraintBuilder {
cb[KeyConst] = value
return cb
}
// Enum adds a constraint that the field must be one of these values.
func (cb ConstraintBuilder) Enum(value ...interface{}) ConstraintBuilder {
cb[KeyEnum] = value
return cb
}
// MultipleOf adds a constraint that the field must be a multiple of this integer.
func (cb ConstraintBuilder) MultipleOf(value int) ConstraintBuilder {
cb[KeyMultipleOf] = value
return cb
}
// Minimum adds a constraint that the field must be greater than or equal to
// this number.
func (cb ConstraintBuilder) Minimum(value int) ConstraintBuilder {
cb[KeyMinimum] = value
return cb
}
// Maximum adds a constraint that the field must be less than or equal to
// this number.
func (cb ConstraintBuilder) Maximum(value int) ConstraintBuilder {
cb[KeyMaximum] = value
return cb
}
// ExclusiveMaximum adds a constraint that the field must be less than this number.
func (cb ConstraintBuilder) ExclusiveMaximum(value int) ConstraintBuilder {
cb[KeyExclusiveMaximum] = value
return cb
}
// ExclusiveMinimum adds a constraint that the field must be greater than this number.
func (cb ConstraintBuilder) ExclusiveMinimum(value int) ConstraintBuilder {
cb[KeyExclusiveMinimum] = value
return cb
}
// MaxLength adds a constraint that the string field must have at most this many characters.
func (cb ConstraintBuilder) MaxLength(value int) ConstraintBuilder {
cb[KeyMaxLength] = value
return cb
}
// MinLength adds a constraint that the string field must have at least this many characters.
func (cb ConstraintBuilder) MinLength(value int) ConstraintBuilder {
cb[KeyMinLength] = value
return cb
}
// Pattern adds a constraint that the string must match the given pattern.
func (cb ConstraintBuilder) Pattern(value string) ConstraintBuilder {
cb[KeyPattern] = value
return cb
}
// MaxItems adds a constraint that the array must have at most this many items.
func (cb ConstraintBuilder) MaxItems(value int) ConstraintBuilder {
cb[KeyMaxItems] = value
return cb
}
// MinItems adds a constraint that the array must have at least this many items.
func (cb ConstraintBuilder) MinItems(value int) ConstraintBuilder {
cb[KeyMinItems] = value
return cb
}
// KeyMaxProperties adds a constraint that the object must have at most this many keys.
func (cb ConstraintBuilder) MaxProperties(value int) ConstraintBuilder {
cb[KeyMaxProperties] = value
return cb
}
// MinProperties adds a constraint that the object must have at least this many keys.
func (cb ConstraintBuilder) MinProperties(value int) ConstraintBuilder {
cb[KeyMinProperties] = value
return cb
}
// Required adds a constraint that the object must have at least these keys.
func (cb ConstraintBuilder) Required(properties ...string) ConstraintBuilder {
cb[KeyRequired] = properties
return cb
}
// PropertyNames adds a constraint that the object property names must match the given schema.
func (cb ConstraintBuilder) PropertyNames(properties map[string]interface{}) ConstraintBuilder {
cb[KeyPropertyNames] = properties
return cb
}
func (cb ConstraintBuilder) Build() map[string]interface{} {
return cb
}
| 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/validation/struct_validator_test.go | pkg/validation/struct_validator_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 validation
import (
"encoding/json"
"fmt"
)
func ExampleErrIfNotOSBName() {
fmt.Println("Good is nil:", ErrIfNotOSBName("google-storage", "my-field") == nil)
fmt.Println("Bad:", ErrIfNotOSBName("google storage", "my-field"))
// Output: Good is nil: true
// Bad: field must match '^[a-zA-Z0-9-\.]+$': my-field
}
func ExampleErrIfNotJSONSchemaType() {
fmt.Println("Good is nil:", ErrIfNotJSONSchemaType("string", "my-field") == nil)
fmt.Println("Bad:", ErrIfNotJSONSchemaType("str", "my-field"))
// Output: Good is nil: true
// Bad: field must match '^(|object|boolean|array|number|string|integer)$': my-field
}
func ExampleErrIfNotHCL() {
fmt.Println("Good HCL is nil:", ErrIfNotHCL(`provider "google" {
credentials = "${file("account.json")}"
project = "my-project-id"
region = "us-central1"
}`, "my-field") == nil)
fmt.Println("Good JSON is nil:", ErrIfNotHCL(`{"a":42, "s":"foo"}`, "my-field") == nil)
fmt.Println("Bad:", ErrIfNotHCL("google storage", "my-field"))
// Output: Good HCL is nil: true
// Good JSON is nil: true
// Bad: invalid HCL: my-field
}
func ExampleErrIfNotTerraformIdentifier() {
fmt.Println("Good is nil:", ErrIfNotTerraformIdentifier("good_id", "my-field") == nil)
fmt.Println("Bad:", ErrIfNotTerraformIdentifier("bad id", "my-field"))
// Output: Good is nil: true
// Bad: field must match '^[a-z_]*$': my-field
}
func ExampleErrIfNotJSON() {
fmt.Println("Good is nil:", ErrIfNotJSON(json.RawMessage("{}"), "my-field") == nil)
fmt.Println("Bad:", ErrIfNotJSON(json.RawMessage(""), "my-field"))
// Output: Good is nil: true
// Bad: invalid JSON: my-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/validation/field_error.go | pkg/validation/field_error.go | // Copyright 2019 the Service Broker Project Authors.
// Copyright 2017 The Knative 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.
// DO NOT EDIT: This file was adapted from github.com/knative/pkg
package validation
import (
"fmt"
"sort"
"strings"
)
// CurrentField is a constant to supply as a fieldPath for when there is
// a problem with the current field itself.
const CurrentField = ""
// FieldError is used to propagate the context of errors pertaining to
// specific fields in a manner suitable for use in a recursive walk, so
// that errors contain the appropriate field context.
// FieldError methods are non-mutating.
// +k8s:deepcopy-gen=true
type FieldError struct {
Message string
Paths []string
// Details contains an optional longer payload.
// +optional
Details string
errors []FieldError
}
// FieldError implements error
var _ error = (*FieldError)(nil)
// ViaField is used to propagate a validation error along a field access.
// For example, if a type recursively validates its "spec" via:
// if err := foo.Spec.Validate(); err != nil {
// // Augment any field paths with the context that they were accessed
// // via "spec".
// return err.ViaField("spec")
// }
func (fe *FieldError) ViaField(prefix ...string) *FieldError {
if fe == nil {
return nil
}
// Copy over message and details, paths will be updated and errors come
// along using .Also().
newErr := &FieldError{
Message: fe.Message,
Details: fe.Details,
}
// Prepend the Prefix to existing errors.
newPaths := make([]string, 0, len(fe.Paths))
for _, oldPath := range fe.Paths {
newPaths = append(newPaths, flatten(append(prefix, oldPath)))
}
newErr.Paths = newPaths
for _, e := range fe.errors {
newErr = newErr.Also(e.ViaField(prefix...))
}
return newErr
}
// ViaIndex is used to attach an index to the next ViaField provided.
// For example, if a type recursively validates a parameter that has a collection:
// for i, c := range spec.Collection {
// if err := doValidation(c); err != nil {
// return err.ViaIndex(i).ViaField("collection")
// }
// }
func (fe *FieldError) ViaIndex(index int) *FieldError {
return fe.ViaField(asIndex(index))
}
// ViaFieldIndex is the short way to chain: err.ViaIndex(bar).ViaField(foo)
func (fe *FieldError) ViaFieldIndex(field string, index int) *FieldError {
return fe.ViaIndex(index).ViaField(field)
}
// ViaKey is used to attach a key to the next ViaField provided.
// For example, if a type recursively validates a parameter that has a collection:
// for k, v := range spec.Bag {
// if err := doValidation(v); err != nil {
// return err.ViaKey(k).ViaField("bag")
// }
// }
func (fe *FieldError) ViaKey(key string) *FieldError {
return fe.ViaField(asKey(key))
}
// ViaFieldKey is the short way to chain: err.ViaKey(bar).ViaField(foo)
func (fe *FieldError) ViaFieldKey(field string, key string) *FieldError {
return fe.ViaKey(key).ViaField(field)
}
// Also collects errors, returns a new collection of existing errors and new errors.
func (fe *FieldError) Also(errs ...*FieldError) *FieldError {
var newErr *FieldError
// collect the current objects errors, if it has any
if !fe.isEmpty() {
newErr = fe.DeepCopy()
} else {
newErr = &FieldError{}
}
// and then collect the passed in errors
for _, e := range errs {
if !e.isEmpty() {
newErr.errors = append(newErr.errors, *e)
}
}
if newErr.isEmpty() {
return nil
}
return newErr
}
func (fe *FieldError) isEmpty() bool {
if fe == nil {
return true
}
return fe.Message == "" && fe.Details == "" && len(fe.errors) == 0 && len(fe.Paths) == 0
}
// normalized returns a flattened copy of all the errors.
func (fe *FieldError) normalized() []*FieldError {
// In case we call normalized on a nil object, return just an empty
// list. This can happen when .Error() is called on a nil object.
if fe == nil {
return []*FieldError(nil)
}
// Allocate errors with at least as many objects as we'll get on the first pass.
errors := make([]*FieldError, 0, len(fe.errors)+1)
// If this FieldError is a leaf, add it.
if fe.Message != "" {
errors = append(errors, &FieldError{
Message: fe.Message,
Paths: fe.Paths,
Details: fe.Details,
})
}
// And then collect all other errors recursively.
for _, e := range fe.errors {
errors = append(errors, e.normalized()...)
}
return errors
}
// Error implements error
func (fe *FieldError) Error() string {
// Get the list of errors as a flat merged list.
normedErrors := merge(fe.normalized())
errs := make([]string, 0, len(normedErrors))
for _, e := range normedErrors {
if e.Details == "" {
errs = append(errs, fmt.Sprintf("%v: %v", e.Message, strings.Join(e.Paths, ", ")))
} else {
errs = append(errs, fmt.Sprintf("%v: %v\n%v", e.Message, strings.Join(e.Paths, ", "), e.Details))
}
}
return strings.Join(errs, "\n")
}
// Helpers ---
func asIndex(index int) string {
return fmt.Sprintf("[%d]", index)
}
func isIndex(part string) bool {
return strings.HasPrefix(part, "[") && strings.HasSuffix(part, "]")
}
func asKey(key string) string {
return fmt.Sprintf("[%s]", key)
}
// flatten takes in a array of path components and looks for chances to flatten
// objects that have index prefixes, examples:
// err([0]).ViaField(bar).ViaField(foo) -> foo.bar.[0] converts to foo.bar[0]
// err(bar).ViaIndex(0).ViaField(foo) -> foo.[0].bar converts to foo[0].bar
// err(bar).ViaField(foo).ViaIndex(0) -> [0].foo.bar converts to [0].foo.bar
// err(bar).ViaIndex(0).ViaIndex(1).ViaField(foo) -> foo.[1].[0].bar converts to foo[1][0].bar
func flatten(path []string) string {
var newPath []string
for _, part := range path {
for _, p := range strings.Split(part, ".") {
if p == CurrentField {
continue
} else if len(newPath) > 0 && isIndex(p) {
newPath[len(newPath)-1] += p
} else {
newPath = append(newPath, p)
}
}
}
return strings.Join(newPath, ".")
}
// mergePaths takes in two string slices and returns the combination of them
// without any duplicate entries.
func mergePaths(a, b []string) []string {
newPaths := make([]string, 0, len(a)+len(b))
newPaths = append(newPaths, a...)
for _, bi := range b {
if !containsString(newPaths, bi) {
newPaths = append(newPaths, bi)
}
}
return newPaths
}
// containsString takes in a string slice and looks for the provided string
// within the slice.
func containsString(slice []string, s string) bool {
for _, item := range slice {
if item == s {
return true
}
}
return false
}
// merge takes in a flat list of FieldErrors and returns back a merged list of
// FieldErrors. FieldErrors have their Paths combined (and de-duped) if their
// Message and Details are the same. Merge will not inspect FieldError.errors.
// Merge will also sort the .Path slice, and the errors slice before returning.
func merge(errs []*FieldError) []*FieldError {
// make a map big enough for all the errors.
m := make(map[string]*FieldError, len(errs))
// Convert errs to a map where the key is <message>-<details> and the value
// is the error. If an error already exists in the map with the same key,
// then the paths will be merged.
for _, e := range errs {
k := key(e)
if v, ok := m[k]; ok {
// Found a match, merge the keys.
v.Paths = mergePaths(v.Paths, e.Paths)
} else {
// Does not exist in the map, save the error.
m[k] = e
}
}
// Take the map made previously and flatten it back out again.
newErrs := make([]*FieldError, 0, len(m))
for _, v := range m {
// While we have access to the merged paths, sort them too.
sort.Slice(v.Paths, func(i, j int) bool { return v.Paths[i] < v.Paths[j] })
newErrs = append(newErrs, v)
}
// Sort the flattened map.
sort.Slice(newErrs, func(i, j int) bool {
if newErrs[i].Message == newErrs[j].Message {
return newErrs[i].Details < newErrs[j].Details
}
return newErrs[i].Message < newErrs[j].Message
})
// return back the merged list of sorted errors.
return newErrs
}
// key returns the key using the fields .Message and .Details.
func key(err *FieldError) string {
return fmt.Sprintf("%s-%s", err.Message, err.Details)
}
// Public helpers ---
// ErrMissingField is a variadic helper method for constructing a FieldError for
// a set of missing fields.
func ErrMissingField(fieldPaths ...string) *FieldError {
return &FieldError{
Message: "missing field(s)",
Paths: fieldPaths,
}
}
// ErrDisallowedFields is a variadic helper method for constructing a FieldError
// for a set of disallowed fields.
func ErrDisallowedFields(fieldPaths ...string) *FieldError {
return &FieldError{
Message: "must not set the field(s)",
Paths: fieldPaths,
}
}
// ErrDisallowedUpdateDeprecatedFields is a variadic helper method for
// constructing a FieldError for updating of deprecated fields.
func ErrDisallowedUpdateDeprecatedFields(fieldPaths ...string) *FieldError {
return &FieldError{
Message: "must not update deprecated field(s)",
Paths: fieldPaths,
}
}
// ErrInvalidArrayValue constructs a FieldError for a repetetive `field`
// at `index` that has received an invalid string value.
func ErrInvalidArrayValue(value interface{}, field string, index int) *FieldError {
return ErrInvalidValue(value, CurrentField).ViaFieldIndex(field, index)
}
// ErrInvalidValue constructs a FieldError for a field that has received an
// invalid string value.
func ErrInvalidValue(value interface{}, fieldPath string) *FieldError {
return &FieldError{
Message: fmt.Sprintf("invalid value: %v", value),
Paths: []string{fieldPath},
}
}
// ErrMissingOneOf is a variadic helper method for constructing a FieldError for
// not having at least one field in a mutually exclusive field group.
func ErrMissingOneOf(fieldPaths ...string) *FieldError {
return &FieldError{
Message: "expected exactly one, got neither",
Paths: fieldPaths,
}
}
// ErrMultipleOneOf is a variadic helper method for constructing a FieldError
// for having more than one field set in a mutually exclusive field group.
func ErrMultipleOneOf(fieldPaths ...string) *FieldError {
return &FieldError{
Message: "expected exactly one, got both",
Paths: fieldPaths,
}
}
// ErrInvalidKeyName is a variadic helper method for constructing a FieldError
// that specifies a key name that is invalid.
func ErrInvalidKeyName(key, fieldPath string, details ...string) *FieldError {
return &FieldError{
Message: fmt.Sprintf("invalid key name %q", key),
Paths: []string{fieldPath},
Details: strings.Join(details, ", "),
}
}
// ErrOutOfBoundsValue constructs a FieldError for a field that has received an
// out of bound value.
func ErrOutOfBoundsValue(value, lower, upper interface{}, fieldPath string) *FieldError {
return &FieldError{
Message: fmt.Sprintf("expected %v <= %v <= %v", lower, value, upper),
Paths: []string{fieldPath},
}
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *FieldError) DeepCopyInto(out *FieldError) {
*out = *in
if in.Paths != nil {
in, out := &in.Paths, &out.Paths
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.errors != nil {
in, out := &in.errors, &out.errors
*out = make([]FieldError, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FieldError.
func (in *FieldError) DeepCopy() *FieldError {
if in == nil {
return nil
}
out := new(FieldError)
in.DeepCopyInto(out)
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/validation/struct_validator.go | pkg/validation/struct_validator.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 validation
import (
"encoding/json"
"fmt"
"net/url"
"regexp"
"github.com/hashicorp/hcl"
)
var (
osbNameRegex = regexp.MustCompile(`^[a-zA-Z0-9-\.]+$`)
terraformIdentifierRegex = regexp.MustCompile(`^[a-z_]*$`)
jsonSchemaTypeRegex = regexp.MustCompile(`^(|object|boolean|array|number|string|integer)$`)
uuidRegex = regexp.MustCompile(`^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}$`)
)
// ErrIfNotHCL returns an error if the value is not valid HCL.
func ErrIfNotHCL(value string, field string) *FieldError {
if _, err := hcl.Parse(value); err == nil {
return nil
}
return &FieldError{
Message: "invalid HCL",
Paths: []string{field},
}
}
// ErrIfNotJSON returns an error if the value is not valid JSON.
func ErrIfNotJSON(value json.RawMessage, field string) *FieldError {
if json.Valid(value) {
return nil
}
return &FieldError{
Message: "invalid JSON",
Paths: []string{field},
}
}
// ErrIfBlank returns an error if the value is a blank string.
func ErrIfBlank(value string, field string) *FieldError {
if value == "" {
return ErrMissingField(field)
}
return nil
}
// ErrIfNil returns an error if the value is nil.
func ErrIfNil(value interface{}, field string) *FieldError {
if value == nil {
return ErrMissingField(field)
}
return nil
}
// ErrIfNotOSBName returns an error if the value is not a valid OSB name.
func ErrIfNotOSBName(value string, field string) *FieldError {
return ErrIfNotMatch(value, osbNameRegex, field)
}
// ErrIfNotJSONSchemaType returns an error if the value is not a valid JSON
// schema type.
func ErrIfNotJSONSchemaType(value string, field string) *FieldError {
return ErrIfNotMatch(value, jsonSchemaTypeRegex, field)
}
// ErrIfNotTerraformIdentifier returns an error if the value is not a valid
// Terraform identifier.
func ErrIfNotTerraformIdentifier(value string, field string) *FieldError {
return ErrIfNotMatch(value, terraformIdentifierRegex, field)
}
// ErrIfNotUUID returns an error if the value is not a valid UUID.
func ErrIfNotUUID(value string, field string) *FieldError {
if uuidRegex.MatchString(value) {
return nil
}
return &FieldError{
Message: "field must be a UUID",
Paths: []string{field},
}
}
// ErrIfNotURL returns an error if the value is not a valid URL.
func ErrIfNotURL(value string, field string) *FieldError {
// Validaiton inspired by: github.com/go-playground/validator/baked_in.go
url, err := url.ParseRequestURI(value)
if err != nil || url.Scheme == "" {
return &FieldError{
Message: "field must be a URL",
Paths: []string{field},
}
}
return nil
}
// ErrIfNotMatch returns an error if the value doesn't match the regex.
func ErrIfNotMatch(value string, regex *regexp.Regexp, field string) *FieldError {
if regex.MatchString(value) {
return nil
}
return ErrMustMatch(value, regex, field)
}
// ErrMustMatch notifies the user a field must match a regex.
func ErrMustMatch(value string, regex *regexp.Regexp, field string) *FieldError {
return &FieldError{
Message: fmt.Sprintf("field must match '%s'", regex.String()),
Paths: []string{field},
}
}
// Validatable indicates that a particular type may have its fields validated.
type Validatable interface {
// Validate checks the validity of this types fields.
Validate() *FieldError
}
// ValidatableTest is a standard way of testing Validatable types.
type ValidatableTest struct {
Object Validatable
Expect error
}
// Testable is a type derived from testing.T
type Testable interface {
Errorf(format string, a ...interface{})
}
// Assert runs the validatae function and fails Testable.
func (vt *ValidatableTest) Assert(t Testable) {
actual := vt.Object.Validate()
expect := vt.Expect
switch {
case expect == nil && actual == nil:
// success
case expect == nil && actual != nil:
t.Errorf("expected: <nil> got: %s", actual.Error())
case expect != nil && actual == nil:
t.Errorf("expected: %s got: <nil>", expect.Error())
case expect.Error() != actual.Error():
t.Errorf("expected: %s got: %s", expect.Error(), actual.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/validation/constraint_builder_test.go | pkg/validation/constraint_builder_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 validation
import (
"reflect"
"testing"
)
func TestConstraintBuilder(t *testing.T) {
// NOTE: Keep keys strings rather than constants in Expected so we can also
// validate that our constants don't get changed.
cases := map[string]struct {
Constraints ConstraintBuilder
Expected map[string]interface{}
}{
"empty": {
Constraints: NewConstraintBuilder().Build(),
Expected: map[string]interface{}{},
},
"annotations": {
Constraints: NewConstraintBuilder().
Description("desc").
Examples("exa", "exb").
Type("string"),
Expected: map[string]interface{}{
"description": "desc",
"examples": []interface{}{"exa", "exb"},
"type": "string",
},
},
"any type": {
Constraints: NewConstraintBuilder().
Enum("a", "b", "c").
Const("exa"),
Expected: map[string]interface{}{
"enum": []interface{}{"a", "b", "c"},
"const": "exa",
},
},
"numeric": {
Constraints: NewConstraintBuilder().
Maximum(3).
Minimum(1).
ExclusiveMaximum(4).
ExclusiveMinimum(0).
MultipleOf(1),
Expected: map[string]interface{}{
"maximum": 3,
"minimum": 1,
"exclusiveMaximum": 4,
"exclusiveMinimum": 0,
"multipleOf": 1,
},
},
"strings": {
Constraints: NewConstraintBuilder().
MaxLength(30).
MinLength(10).
Pattern("^[A-Za-z]+[A-Za-z0-9]+$"),
Expected: map[string]interface{}{
"maxLength": 30,
"minLength": 10,
"pattern": "^[A-Za-z]+[A-Za-z0-9]+$",
},
},
"arrays": {
Constraints: NewConstraintBuilder().
MaxItems(30).
MinItems(10),
Expected: map[string]interface{}{
"maxItems": 30,
"minItems": 10,
},
},
"objects": {
Constraints: NewConstraintBuilder().
MaxProperties(30).
MinProperties(10).
Required("a", "b", "c").
PropertyNames(map[string]interface{}{"type": "string"}),
Expected: map[string]interface{}{
"maxProperties": 30,
"minProperties": 10,
"required": []string{"a", "b", "c"},
"propertyNames": map[string]interface{}{"type": "string"},
},
},
"secondOverwritesFirst": {
Constraints: NewConstraintBuilder().MaxLength(3).MaxLength(5).Build(),
Expected: map[string]interface{}{
KeyMaxLength: 5,
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := tc.Constraints.Build()
if !reflect.DeepEqual(tc.Expected, actual) {
t.Errorf("Error constructing constraints, expected: %#v got: %#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/validation/field_error_test.go | pkg/validation/field_error_test.go | // Copyright 2019 the Service Broker Project Authors.
// Copyright 2017 The Knative 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.
// DO NOT EDIT: This file was adapted from github.com/knative/pkg
package validation
import (
"fmt"
"strconv"
"strings"
"testing"
"time"
)
type testStruct struct {
Name string `json:"name"`
}
type unexported struct {
unexportedField int
}
func TestFieldError(t *testing.T) {
tests := []struct {
name string
err *FieldError
prefixes [][]string
want string
}{{
name: "simple single no propagation",
err: &FieldError{
Message: "hear me roar",
Paths: []string{"foo.bar"},
},
want: "hear me roar: foo.bar",
}, {
name: "simple single propagation",
err: &FieldError{
Message: `invalid value "blah"`,
Paths: []string{"foo"},
},
prefixes: [][]string{{"bar"}, {"baz", "ugh"}, {"hoola"}},
want: `invalid value "blah": hoola.baz.ugh.bar.foo`,
}, {
name: "simple multiple propagation",
err: &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo", "bar"},
},
prefixes: [][]string{{"baz", "ugh"}},
want: "invalid field(s): baz.ugh.bar, baz.ugh.foo",
}, {
name: "multiple propagation with details",
err: &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo", "bar"},
Details: `I am a long
long
loooong
Body.`,
},
prefixes: [][]string{{"baz", "ugh"}},
want: `invalid field(s): baz.ugh.bar, baz.ugh.foo
I am a long
long
loooong
Body.`,
}, {
name: "single propagation, empty start",
err: &FieldError{
Message: "invalid field(s)",
// We might see this validating a scalar leaf.
Paths: []string{CurrentField},
},
prefixes: [][]string{{"baz", "ugh"}},
want: "invalid field(s): baz.ugh",
}, {
name: "single propagation, no paths",
err: &FieldError{
Message: "invalid field(s)",
Paths: nil,
},
prefixes: [][]string{{"baz", "ugh"}},
want: "invalid field(s): ",
}, {
name: "nil propagation",
err: nil,
prefixes: [][]string{{"baz", "ugh"}},
}, {
name: "missing field propagation",
err: ErrMissingField("foo", "bar"),
prefixes: [][]string{{"baz"}},
want: "missing field(s): baz.bar, baz.foo",
}, {
name: "missing disallowed propagation",
err: ErrDisallowedFields("foo", "bar"),
prefixes: [][]string{{"baz"}},
want: "must not set the field(s): baz.bar, baz.foo",
}, {
name: "invalid value propagation",
err: ErrInvalidValue("foo", "bar"),
prefixes: [][]string{{"baz"}},
want: `invalid value: foo: baz.bar`,
}, {
name: "invalid value propagation (int)",
err: ErrInvalidValue(5, "bar"),
prefixes: [][]string{{"baz"}},
want: `invalid value: 5: baz.bar`,
}, {
name: "invalid value propagation (duration)",
err: ErrInvalidValue(5*time.Second, "bar"),
prefixes: [][]string{{"baz"}},
want: `invalid value: 5s: baz.bar`,
}, {
name: "missing mutually exclusive fields",
err: ErrMissingOneOf("foo", "bar"),
prefixes: [][]string{{"baz"}},
want: `expected exactly one, got neither: baz.bar, baz.foo`,
}, {
name: "multiple mutually exclusive fields",
err: ErrMultipleOneOf("foo", "bar"),
prefixes: [][]string{{"baz"}},
want: `expected exactly one, got both: baz.bar, baz.foo`,
}, {
name: "invalid key name",
err: ErrInvalidKeyName("b@r", "foo[0].name",
"can not use @", "do not try"),
prefixes: [][]string{{"baz"}},
want: `invalid key name "b@r": baz.foo[0].name
can not use @, do not try`,
}, {
name: "invalid key name with details array",
err: ErrInvalidKeyName("b@r", "foo[0].name",
[]string{"can not use @", "do not try"}...),
prefixes: [][]string{{"baz"}},
want: `invalid key name "b@r": baz.foo[0].name
can not use @, do not try`,
}, {
name: "disallowed update deprecated fields",
err: ErrDisallowedUpdateDeprecatedFields("foo", "bar"),
prefixes: [][]string{{"baz"}},
want: `must not update deprecated field(s): baz.bar, baz.foo`,
}, {
name: "very complex to simple",
err: func() *FieldError {
fe := &FieldError{
Message: "First",
Paths: []string{"A", "B", "C"},
}
fe = fe.Also(fe).Also(fe).Also(fe).Also(fe)
fe = fe.Also(&FieldError{
Message: "Second",
Paths: []string{"Z", "X", "Y"},
})
fe = fe.Also(fe).Also(fe).Also(fe).Also(fe)
return fe
}(),
want: `First: A, B, C
Second: X, Y, Z`,
}, {
name: "exponentially grows",
err: func() *FieldError {
fe := &FieldError{
Message: "Top",
Paths: []string{"A", "B", "C"},
}
for _, p := range []string{"3", "2", "1"} {
for i := 0; i < 3; i++ {
fe = fe.Also(fe)
}
fe = fe.ViaField(p)
}
return fe
}(),
want: `Top: 1.2.3.A, 1.2.3.B, 1.2.3.C`,
}, {
name: "path grows but details are different",
err: func() *FieldError {
fe := &FieldError{
Message: "Top",
Paths: []string{"A", "B", "C"},
}
for _, p := range []string{"3", "2", "1"} {
e := fe.ViaField(p)
e.Details = fmt.Sprintf("here at %s", p)
for i := 0; i < 3; i++ {
fe = fe.Also(e)
}
}
return fe
}(),
want: `Top: A, B, C
Top: 1.A, 1.B, 1.C
here at 1
Top: 1.2.A, 1.2.B, 1.2.C, 2.A, 2.B, 2.C
here at 2
Top: 1.2.3.A, 1.2.3.B, 1.2.3.C, 1.3.A, 1.3.B, 1.3.C, 2.3.A, 2.3.B, 2.3.C, 3.A, 3.B, 3.C
here at 3`,
}, {
name: "very complex to complex",
err: func() *FieldError {
fe := &FieldError{
Message: "First",
Paths: []string{"A", "B", "C"},
}
fe = fe.ViaField("one").Also(fe).ViaField("two").Also(fe).ViaField("three").Also(fe)
fe = fe.Also(&FieldError{
Message: "Second",
Paths: []string{"Z", "X", "Y"},
})
return fe
}(),
want: `First: A, B, C, three.A, three.B, three.C, three.two.A, three.two.B, three.two.C, three.two.one.A, three.two.one.B, three.two.one.C
Second: X, Y, Z`,
}, {
name: "out of bound value",
err: ErrOutOfBoundsValue("a", "b", "c", "string"),
prefixes: [][]string{{"spec"}},
want: `expected b <= a <= c: spec.string`,
}, {
name: "out of bound value (int)",
err: ErrOutOfBoundsValue(-1, 0, 5, "timeout"),
prefixes: [][]string{{"spec"}},
want: `expected 0 <= -1 <= 5: spec.timeout`,
}, {
name: "out of bound value (time.Duration)",
err: ErrOutOfBoundsValue(1*time.Second, 2*time.Second, 5*time.Second, "timeout"),
prefixes: [][]string{{"spec"}},
want: `expected 2s <= 1s <= 5s: spec.timeout`,
}}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fe := test.err
// Simulate propagation up a call stack.
for _, prefix := range test.prefixes {
fe = fe.ViaField(prefix...)
}
if test.want != "" {
if got, want := fe.Error(), test.want; got != want {
t.Errorf("%s: Error() = %v, wanted %v", test.name, got, want)
}
} else if fe != nil {
t.Errorf("%s: ViaField() = %v, wanted nil", test.name, fe)
}
})
}
}
func TestViaIndexOrKeyFieldError(t *testing.T) {
tests := []struct {
name string
err *FieldError
prefixes [][]string
want string
}{{
name: "nil",
err: nil,
want: "",
}, {
name: "nil with prefix",
err: nil,
prefixes: [][]string{{"INDEX:2"}, {"KEY:B"}, {"FIELDINDEX:6,AAA"}, {"FIELDKEY:bee,AAA"}},
want: "",
}, {
name: "simple single no propagation",
err: &FieldError{
Message: "hear me roar",
Paths: []string{"bar"},
},
prefixes: [][]string{{"INDEX:3", "INDEX:2", "INDEX:1", "foo"}},
want: "hear me roar: foo[1][2][3].bar",
}, {
name: "simple key",
err: &FieldError{
Message: "hear me roar",
Paths: []string{"bar"},
},
prefixes: [][]string{{"KEY:C", "KEY:B", "KEY:A", "foo"}},
want: "hear me roar: foo[A][B][C].bar",
}, {
name: "missing field propagation",
err: ErrMissingField("foo", "bar"),
prefixes: [][]string{{"[2]", "baz"}},
want: "missing field(s): baz[2].bar, baz[2].foo",
}, {
name: "invalid key name",
err: ErrInvalidKeyName("b@r", "name",
"can not use @", "do not try"),
prefixes: [][]string{{"baz", "INDEX:0", "foo"}},
want: `invalid key name "b@r": foo[0].baz.name
can not use @, do not try`,
}, {
name: "invalid key name with keys",
err: ErrInvalidKeyName("b@r", "name",
"can not use @", "do not try"),
prefixes: [][]string{{"baz", "INDEX:0", "foo"}, {"bar", "KEY:A", "boo"}},
want: `invalid key name "b@r": boo[A].bar.foo[0].baz.name
can not use @, do not try`,
}, {
name: "multi prefixes provided",
err: &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo"},
},
prefixes: [][]string{{"INDEX:2"}, {"bee"}, {"INDEX:0"}, {"baa", "baz", "ugh"}},
want: "invalid field(s): ugh.baz.baa[0].bee[2].foo",
}, {
name: "use helper viaFieldIndex",
err: &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo"},
},
prefixes: [][]string{{"FIELDINDEX:bee,2"}, {"FIELDINDEX:baa,0"}, {"baz", "ugh"}},
want: "invalid field(s): ugh.baz.baa[0].bee[2].foo",
}, {
name: "use helper viaFieldKey",
err: &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo"},
},
prefixes: [][]string{{"FIELDKEY:bee,AAA"}, {"FIELDKEY:baa,BBB"}, {"baz", "ugh"}},
want: "invalid field(s): ugh.baz.baa[BBB].bee[AAA].foo",
}, {
name: "bypass helpers",
err: &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo"},
},
prefixes: [][]string{{"[2]"}, {"[1]"}, {"bar"}},
want: "invalid field(s): bar[1][2].foo",
}, {
name: "multi paths provided",
err: &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo", "bar"},
},
prefixes: [][]string{{"INDEX:0"}, {"index"}, {"KEY:A"}, {"map"}},
want: "invalid field(s): map[A].index[0].bar, map[A].index[0].foo",
}, {
name: "manual index",
err: func() *FieldError {
// Example, return an error in a loop:
// for i, item := spec.myList {
// err := item.validate().ViaIndex(i).ViaField("myList")
// if err != nil {
// return err
// }
// }
// --> I expect path to be myList[i].foo
err := &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo"},
}
err = err.ViaIndex(0).ViaField("bar")
err = err.ViaIndex(2).ViaIndex(1).ViaField("baz")
err = err.ViaIndex(3).ViaIndex(4).ViaField("boof")
return err
}(),
want: "invalid field(s): boof[4][3].baz[1][2].bar[0].foo",
}, {
name: "manual multiple index",
err: func() *FieldError {
err := &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo"},
}
err = err.ViaField("bear", "[1]", "[2]", "[3]", "baz", "]xxx[").ViaField("bar")
return err
}(),
want: "invalid field(s): bar.bear[1][2][3].baz.]xxx[.foo",
}, {
name: "manual keys",
err: func() *FieldError {
err := &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo"},
}
err = err.ViaKey("A").ViaField("bar")
err = err.ViaKey("CCC").ViaKey("BB").ViaField("baz")
err = err.ViaKey("E").ViaKey("F").ViaField("jar")
return err
}(),
want: "invalid field(s): jar[F][E].baz[BB][CCC].bar[A].foo",
}, {
name: "manual index and keys",
err: func() *FieldError {
err := &FieldError{
Message: "invalid field(s)",
Paths: []string{"foo", "faa"},
}
err = err.ViaKey("A").ViaField("bar")
err = err.ViaIndex(1).ViaField("baz")
err = err.ViaKey("E").ViaIndex(0).ViaField("jar")
return err
}(),
want: "invalid field(s): jar[0][E].baz[1].bar[A].faa, jar[0][E].baz[1].bar[A].foo",
}, {
name: "leaf field error with index",
err: func() *FieldError {
return ErrInvalidArrayValue("kapot", "indexed", 5)
}(),
want: `invalid value: kapot: indexed[5]`,
}, {
name: "leaf field error with index (int)",
err: func() *FieldError {
return ErrInvalidArrayValue(42, "indexed", 5)
}(),
want: `invalid value: 42: indexed[5]`,
}, {
name: "nil propagation",
err: nil,
prefixes: [][]string{{"baz", "ugh", "INDEX:0", "KEY:A"}},
}}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fe := test.err
// Simulate propagation up a call stack.
for _, prefix := range test.prefixes {
for _, p := range prefix {
if strings.HasPrefix(p, "INDEX") {
index := strings.Split(p, ":")
fe = fe.ViaIndex(makeIndex(index[1]))
} else if strings.HasPrefix(p, "FIELDINDEX") {
index := strings.Split(p, ":")
fe = fe.ViaFieldIndex(makeFieldIndex(index[1]))
} else if strings.HasPrefix(p, "KEY") {
key := strings.Split(p, ":")
fe = fe.ViaKey(makeKey(key[1]))
} else if strings.HasPrefix(p, "FIELDKEY") {
index := strings.Split(p, ":")
fe = fe.ViaFieldKey(makeFieldKey(index[1]))
} else {
fe = fe.ViaField(p)
}
}
}
if test.want != "" {
if got, want := fe.Error(), test.want; got != want {
t.Errorf("%s: Error() = %q, wanted %q", test.name, got, want)
}
} else if fe != nil {
t.Errorf("%s: ViaField() = %v, wanted nil", test.name, fe)
}
})
}
}
func TestNilError(t *testing.T) {
var err *FieldError
if got, want := err.Error(), ""; got != want {
t.Errorf("got %v, wanted %v", got, want)
}
}
func TestAlso(t *testing.T) {
tests := []struct {
name string
err *FieldError
also []FieldError
prefixes [][]string
want string
}{{
name: "nil",
err: nil,
also: []FieldError{{
Message: "also this",
Paths: []string{"woo"},
}},
prefixes: [][]string{{"foo"}},
want: "also this: foo.woo",
}, {
name: "nil all the way",
err: nil,
also: []FieldError{{}},
want: "",
}, {
name: "simple",
err: &FieldError{
Message: "hear me roar",
Paths: []string{"bar"},
},
also: []FieldError{{
Message: "also this",
Paths: []string{"woo"},
}},
prefixes: [][]string{{"foo", "[A]", "[B]", "[C]"}},
want: `also this: foo[A][B][C].woo
hear me roar: foo[A][B][C].bar`,
}, {
name: "lots of also",
err: &FieldError{
Message: "knock knock",
Paths: []string{"foo"},
},
also: []FieldError{{
Message: "also this",
Paths: []string{"A"},
}, {
Message: "and this",
Paths: []string{"B"},
}, {
Message: "not without this",
Paths: []string{"C"},
}},
prefixes: [][]string{{"bar"}},
want: `also this: bar.A
and this: bar.B
knock knock: bar.foo
not without this: bar.C`,
}}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fe := test.err
for _, err := range test.also {
fe = fe.Also(&err)
}
// Simulate propagation up a call stack.
for _, prefix := range test.prefixes {
fe = fe.ViaField(prefix...)
}
if test.want != "" {
if got, want := fe.Error(), test.want; got != want {
t.Errorf("%s: Error() = %v, wanted %v", test.name, got, want)
}
} else if fe != nil {
t.Errorf("%s: ViaField() = %v, wanted nil", test.name, fe)
}
})
}
}
func TestMergeFieldErrors(t *testing.T) {
tests := []struct {
name string
err *FieldError
also []FieldError
prefixes [][]string
want string
}{{
name: "simple",
err: &FieldError{
Message: "A simple error message",
Paths: []string{"bar"},
},
also: []FieldError{{
Message: "A simple error message",
Paths: []string{"foo"},
}},
want: `A simple error message: bar, foo`,
}, {
name: "conflict",
err: &FieldError{
Message: "A simple error message",
Paths: []string{"bar", "foo"},
},
also: []FieldError{{
Message: "A simple error message",
Paths: []string{"foo"},
}},
want: `A simple error message: bar, foo`,
}, {
name: "lots of also",
err: (&FieldError{
Message: "this error",
Paths: []string{"bar", "foo"},
}).Also(&FieldError{
Message: "another",
Paths: []string{"right", "left"},
}).ViaField("head"),
also: []FieldError{{
Message: "An alpha error message",
Paths: []string{"A"},
}, {
Message: "An alpha error message",
Paths: []string{"B"},
}, {
Message: "An alpha error message",
Paths: []string{"B"},
}, {
Message: "An alpha error message",
Paths: []string{"B"},
}, {
Message: "An alpha error message",
Paths: []string{"B"},
}, {
Message: "An alpha error message",
Paths: []string{"B"},
}, {
Message: "An alpha error message",
Paths: []string{"B"},
}, {
Message: "An alpha error message",
Paths: []string{"C"},
}, {
Message: "An alpha error message",
Paths: []string{"D"},
}, {
Message: "this error",
Paths: []string{"foo"},
Details: "devil is in the details",
}, {
Message: "this error",
Paths: []string{"foo"},
Details: "more details",
}},
prefixes: [][]string{{"this"}},
want: `An alpha error message: this.A, this.B, this.C, this.D
another: this.head.left, this.head.right
this error: this.head.bar, this.head.foo
this error: this.foo
devil is in the details
this error: this.foo
more details`,
}}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fe := test.err
for _, err := range test.also {
fe = fe.Also(&err)
}
// Simulate propagation up a call stack.
for _, prefix := range test.prefixes {
fe = fe.ViaField(prefix...)
}
if test.want != "" {
got := fe.Error()
if got != test.want {
t.Errorf("%s: Error() = %v, wanted %v", test.name, got, test.want)
}
} else if fe != nil {
t.Errorf("%s: ViaField() = %v, wanted nil", test.name, fe)
}
})
}
}
func TestAlsoStaysNil(t *testing.T) {
var err *FieldError
if err != nil {
t.Errorf("expected nil, got %v, wanted nil", err)
}
err = err.Also(nil)
if err != nil {
t.Errorf("expected nil, got %v, wanted nil", err)
}
err = err.ViaField("nil").Also(nil)
if err != nil {
t.Errorf("expected nil, got %v, wanted nil", err)
}
err = err.Also(&FieldError{})
if err != nil {
t.Errorf("expected nil, got %v, wanted nil", err)
}
}
func TestFlatten(t *testing.T) {
tests := []struct {
name string
indices []string
want string
}{{
name: "simple",
indices: strings.Split("foo.[1]", "."),
want: "foo[1]",
}, {
name: "no brackets",
indices: strings.Split("foo.bar", "."),
want: "foo.bar",
}, {
name: "err([0]).ViaField(bar).ViaField(foo)",
indices: strings.Split("foo.bar.[0]", "."),
want: "foo.bar[0]",
}, {
name: "err(bar).ViaIndex(0).ViaField(foo)",
indices: strings.Split("foo.[0].bar", "."),
want: "foo[0].bar",
}, {
name: "err(bar).ViaField(foo).ViaIndex(0)",
indices: strings.Split("[0].foo.bar", "."),
want: "[0].foo.bar",
}, {
name: "err(bar).ViaIndex(0).ViaIndex[1].ViaField(foo)",
indices: strings.Split("foo.[1].[0].bar", "."),
want: "foo[1][0].bar",
}, {
name: "err(foo).ViaField(bar).ViaIndex[0].ViaField(baz)",
indices: []string{"foo", "bar.[0].baz"},
want: "foo.bar[0].baz",
}}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got, want := flatten(test.indices), test.want; got != want {
t.Errorf("got: %q, want %q", got, want)
}
})
}
}
func makeIndex(index string) int {
all := strings.Split(index, ",")
if i, err := strconv.Atoi(all[0]); err == nil {
return i
}
return -1
}
func makeFieldIndex(fi string) (string, int) {
all := strings.Split(fi, ",")
if i, err := strconv.Atoi(all[1]); err == nil {
return all[0], i
}
return "error", -1
}
func makeKey(key string) string {
all := strings.Split(key, ",")
return all[0]
}
func makeFieldKey(fk string) (string, string) {
all := strings.Split(fk, ",")
return all[0], all[1]
}
| 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/generator/types.go | pkg/generator/types.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 generator
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
// CatalogDocumentation generates markdown documentation for the service catalog
// of the given registry. Returns all content in one string.
func CatalogDocumentation(registry broker.BrokerRegistry) string {
const contentSeparator = "\n--------------------------------------------------------------------------------\n"
out := ""
services := registry.GetAllServices()
for _, svc := range services {
out += generateServiceDocumentation(svc)
out += contentSeparator
}
return cleanMdOutput(out)
}
// CatalogDocumentationToDir generates markdown documentation for the service catalog
// of the given registry. Generated documentation is saved under given `dstDir` with such layout:
//
// ./{dstDir}
// ├── classes
// │ ├── {class_name}.md # contains all information about given service class
// │ └── ...
// └── use.md # contains table of contents (ToC) about all generated service class documentation
//
func CatalogDocumentationToDir(registry broker.BrokerRegistry, dstDir string) {
const (
mdExt = ".md"
classDir = "classes"
perms = 0644
)
classesDir := filepath.Join(dstDir, classDir)
if err := ensureDir(classesDir); err != nil {
log.Fatalf("Cannot create directory for storing broker classes documentation: %v", err)
}
var tocServiceClasses []ToCServiceClass
for _, svc := range registry.GetAllServices() {
out := generateServiceDocumentation(svc)
out = cleanMdOutput(out)
saveClassPath := filepath.Join(classesDir, svc.Name+mdExt)
err := ioutil.WriteFile(saveClassPath, []byte(out), perms)
if err != nil {
log.Fatalf("Cannot save %s documentation class into %s: %v", svc.Name, saveClassPath, err)
}
tocClassPath, err := filepath.Rel(dstDir, saveClassPath)
if err != nil {
log.Fatalf("Cannot resolve relative path to %s file: %v", saveClassPath, err)
}
tocServiceClasses = append(tocServiceClasses, ToCServiceClass{
DisplayName: svc.DisplayName,
FilePath: tocClassPath,
})
}
toc := generateServiceClassesToC(tocServiceClasses)
tocFileName := filepath.Join(dstDir, "use.md")
if err := ioutil.WriteFile(tocFileName, []byte(toc), perms); err != nil {
log.Fatalf("Cannot save documentation from %s class into %s", "", "")
}
}
type ToCServiceClass struct {
DisplayName string
FilePath string
}
func generateServiceClassesToC(tocServiceClasses []ToCServiceClass) string {
tocTemplateText := `# GCP Service Broker usage
# Overview
The GCP service broker is a tool that developers use to provision access Google Cloud resources. The service broker currently supports a list of built-in services.
Read about creating and binding specific GCP services:
{{range .serviceClasses}}
- [{{ .DisplayName }}]({{ .FilePath }})
{{ end -}}
`
vars := map[string]interface{}{
"serviceClasses": tocServiceClasses,
}
return render(tocTemplateText, vars, nil)
}
func ensureDir(dirPath string) error {
err := os.Mkdir(dirPath, os.ModePerm)
if err != nil && !os.IsExist(err) {
return err
}
return nil
}
// generateServiceDocumentation creates documentation for a single catalog entry
func generateServiceDocumentation(svc *broker.ServiceDefinition) string {
catalog, err := svc.CatalogEntry()
if err != nil {
log.Fatalf("Error getting catalog entry for service %s, %v", svc.Name, err)
}
vars := map[string]interface{}{
"catalog": catalog,
"metadata": catalog.Metadata,
"bindIn": svc.BindInputVariables,
"bindOut": svc.BindOutputVariables,
"provisionInputVars": svc.ProvisionInputVariables,
"examples": svc.Examples,
}
funcMap := template.FuncMap{
"code": mdCode,
"join": strings.Join,
"varNotes": varNotes,
"jsonCodeBlock": jsonCodeBlock,
"exampleCommands": func(example broker.ServiceExample) string {
planName := "unknown-plan"
for _, plan := range catalog.Plans {
if plan.ID == example.PlanId {
planName = plan.Name
}
}
params, err := json.Marshal(example.ProvisionParams)
if err != nil {
return err.Error()
}
provision := fmt.Sprintf("$ cf create-service %s %s my-%s-example -c `%s`", catalog.Name, planName, catalog.Name, params)
params, err = json.Marshal(example.BindParams)
if err != nil {
return err.Error()
}
bind := fmt.Sprintf("$ cf bind-service my-app my-%s-example -c `%s`", catalog.Name, params)
return provision + "\n" + bind
},
}
templateText := `
# <a name="{{ .catalog.Name }}"></a>  {{ .metadata.DisplayName }}
{{ .metadata.LongDescription }}
* [Documentation]({{.metadata.DocumentationUrl }})
* [Support]({{ .metadata.SupportUrl }})
* Catalog Metadata ID: {{code .catalog.ID}}
* Tags: {{ join .catalog.Tags ", " }}
* Service Name: {{ code .catalog.Name }}
## Provisioning
**Request Parameters**
{{ if eq (len .provisionInputVars) 0 }}_No parameters supported._{{ end }}
{{ range $i, $var := .provisionInputVars }} * {{ varNotes $var }}
{{ end }}
## Binding
**Request Parameters**
{{ if eq (len .bindIn) 0 }}_No parameters supported._{{ end }}
{{ range $i, $var := .bindIn }} * {{ varNotes $var }}
{{ end }}
**Response Parameters**
{{ range $i, $var := .bindOut }} * {{ varNotes $var }}
{{ end }}
## Plans
The following plans are built-in to the GCP Service Broker and may be overridden
or disabled by the broker administrator.
{{ if eq (len .catalog.Plans) 0 }}_No plans available_{{ end }}
{{ range $i, $plan := .catalog.Plans -}}
* **{{code $plan.Name }}**
* Plan ID: {{code $plan.ID}}.
* Description: {{ $plan.Description }}
* This plan {{ if eq (len $plan.ProvisionOverrides) 0 -}} doesn't override {{- else -}} overrides the following {{- end}} user variables on provision.
{{ range $k, $v := $plan.ProvisionOverrides}} * {{ code $k }} = {{code $v}}
{{ end }} * This plan {{ if eq (len $plan.BindOverrides) 0 -}} doesn't override {{- else -}} overrides the following {{- end}} user variables on bind.
{{ range $k, $v := $plan.BindOverrides}} * {{ code $k }} = {{code $v}}
{{ end }}
{{- end }}
## Examples
{{ if eq (len .examples) 0 }}_No examples._{{ end }}
{{ range $i, $example := .examples}}
### {{ $example.Name }}
{{ $example.Description }}
Uses plan: {{ code $example.PlanId }}.
**Provision**
{{ jsonCodeBlock $example.ProvisionParams }}
**Bind**
{{ jsonCodeBlock $example.BindParams }}
**Cloud Foundry Example**
<pre>
{{exampleCommands $example}}
</pre>
{{ end }}
`
return render(templateText, vars, funcMap)
}
func render(tmplText string, vars interface{}, funcMap template.FuncMap) string {
tmpl, err := template.New("rendered").Funcs(funcMap).Parse(tmplText)
if err != nil {
log.Fatalf("parsing: %s", err)
}
// Run the template to verify the output.
var buf bytes.Buffer
err = tmpl.Execute(&buf, vars)
if err != nil {
log.Fatalf("execution: %s", err)
}
return buf.String()
}
func mdCode(text interface{}) string {
return fmt.Sprintf("`%v`", text)
}
func varNotes(variable broker.BrokerVariable) string {
out := fmt.Sprintf("`%s` _%s_ - ", variable.FieldName, variable.Type)
if variable.Required {
out += "**Required** "
}
out += cleanLines(variable.Details)
if variable.Default != nil {
out += fmt.Sprintf(" Default: `%v`.", variable.Default)
}
bullets := constraintsToDoc(variable.ToSchema())
if len(bullets) > 0 {
out += "\n * "
out += strings.Join(bullets, "\n * ")
}
return out
}
// constraintsToDoc converts a map of JSON Schema validation key/values to human-readable bullet points.
func constraintsToDoc(schema map[string]interface{}) []string {
// We use an anonymous struct rather than a map to get a strict ordering of
// constraints so they are generated consistently in documentation.
// Not all JSON Schema constraints can be cleanly expressed in this format,
// nor do we use them all so some are missing.
constraintFormatters := []struct {
SchemaKey string
DocString string
}{
// Schema Annotations
{validation.KeyExamples, "Examples: %+v."},
// Validation for any instance type
{validation.KeyEnum, "The value must be one of: %+v."},
{validation.KeyConst, "The value must be: `%v`."},
// Validation keywords for numeric instances
{validation.KeyMultipleOf, "The value must be a multiple of %v."},
{validation.KeyMaximum, "The value must be less than or equal to %v."},
{validation.KeyExclusiveMaximum, "The value must be strictly less than %v."},
{validation.KeyMinimum, "The value must be greater than or equal to %v."},
{validation.KeyExclusiveMaximum, "The value must be strictly greater than %v."},
// Validation keywords for strings
{validation.KeyMaxLength, "The string must have at most %v characters."},
{validation.KeyMinLength, "The string must have at least %v characters."},
{validation.KeyPattern, "The string must match the regular expression `%v`."},
// Validation keywords for arrays
{validation.KeyMaxItems, "The array must have at most %v items."},
{validation.KeyMinItems, "The array must have at least %v items."},
// Validation keywords for objects
{validation.KeyMaxProperties, "The object must have at most %v properties."},
{validation.KeyMinProperties, "The object must have at least %v properties."},
{validation.KeyRequired, "The following properties are required: %v."},
{validation.KeyMaxProperties, "Property names must match the JSON Schema: `%+v`."},
}
var bullets []string
for _, formatter := range constraintFormatters {
if v, ok := schema[formatter.SchemaKey]; ok {
bullets = append(bullets, fmt.Sprintf(formatter.DocString, v))
}
}
return bullets
}
// cleanLines concatenates multiple lines of text, trimming any leading/trailing
// whitespace
func cleanLines(text string) string {
lines := strings.Split(text, "\n")
for i, l := range lines {
lines[i] = strings.TrimSpace(l)
}
return strings.Join(lines, " ")
}
// jsonCodeBlock formats the value as pretty JSON and wraps it in a Github style
// hilighted block.
func jsonCodeBlock(value interface{}) string {
block, _ := json.MarshalIndent(value, "", " ")
return fmt.Sprintf("```javascript\n%s\n```", block)
}
| 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/generator/forms.go | pkg/generator/forms.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 generator
import (
"fmt"
"log"
"sort"
"strings"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/toggles"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
yaml "gopkg.in/yaml.v2"
)
// TileFormsSections holds the top level fields in tile.yml responsible for
// the forms.
// https://docs.pivotal.io/tiledev/2-2/tile-structure.html
type TileFormsSections struct {
Forms []Form `yaml:"forms"`
ServicePlanForms []Form `yaml:"service_plan_forms,omitempty"`
}
// Form is an Ops Manager compatible form definition used to generate forms.
// See https://docs.pivotal.io/tiledev/2-2/product-template-reference.html#form-properties
// for details about the fields.
type Form struct {
Name string `yaml:"name"`
Label string `yaml:"label"`
Description string `yaml:"description"`
Optional bool `yaml:"optional,omitempty"` // optional, default false
Properties []FormProperty `yaml:"properties"`
}
// FormOption is an enumerated element for FormProperties that can be selected
// from. Name is the value and label is the human-readable display name.
type FormOption struct {
Name string `yaml:"name"`
Label string `yaml:"label"`
}
// FormProperty holds a single form element in a Ops Manager form.
type FormProperty struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Default interface{} `yaml:"default,omitempty"`
Label string `yaml:"label,omitempty"`
Description string `yaml:"description,omitempty"`
Configurable bool `yaml:"configurable,omitempty"` // optional, default false
Options []FormOption `yaml:"options,omitempty"`
Optional bool `yaml:"optional,omitempty"` // optional, default false
}
// GenerateFormsString creates all the forms for the user to fill out in the PCF tile
// and returns it as a string.
func GenerateFormsString() string {
response, err := yaml.Marshal(GenerateForms())
if err != nil {
log.Fatalf("Error marshaling YAML: %s", err)
}
return string(response)
}
// GenerateForms creates all the forms for the user to fill out in the PCF tile.
func GenerateForms() TileFormsSections {
// Add new forms at the bottom of the list because the order is reflected
// in the generated UI and we don't want to mix things up on users.
return TileFormsSections{
Forms: []Form{
generateServiceAccountForm(),
generateDatabaseForm(),
generateBrokerpakForm(),
generateFeatureFlagForm(),
generateDefaultOverrideForm(),
},
ServicePlanForms: append(generateServicePlanForms(), brokerpakConfigurationForm()),
}
}
// generateDefaultOverrideForm generates a form for users to override the
// defaults in a plan.
func generateDefaultOverrideForm() Form {
builtinServices := builtin.BuiltinBrokerRegistry()
formElements := []FormProperty{}
for _, svc := range builtinServices.GetAllServices() {
entry, err := svc.CatalogEntry()
if err != nil {
log.Fatalf("Error getting catalog entry for service %s, %v", svc.Name, err)
}
if !svc.IsRoleWhitelistEnabled() {
continue
}
provisionForm := FormProperty{
Name: strings.ToLower(utils.PropertyToEnv(svc.ProvisionDefaultOverrideProperty())),
Label: fmt.Sprintf("Provision default override %s instances.", entry.Metadata.DisplayName),
Description: "A JSON object with key/value pairs. Keys MUST be the name of a user-defined provision property and values are the alternative default.",
Type: "text",
Default: "{}",
Configurable: true,
}
formElements = append(formElements, provisionForm)
bindForm := FormProperty{
Name: strings.ToLower(utils.PropertyToEnv(svc.BindDefaultOverrideProperty())),
Label: fmt.Sprintf("Bind default override %s instances.", entry.Metadata.DisplayName),
Description: "A JSON object with key/value pairs. Keys MUST be the name of a user-defined bind property and values are the alternative default.",
Type: "text",
Default: "{}",
Configurable: true,
}
formElements = append(formElements, bindForm)
}
return Form{
Name: "default_override",
Label: "Default Overrides",
Description: "Override the default values your users get when provisioning.",
Properties: formElements,
}
}
// generateDatabaseForm generates the form for configuring database settings.
func generateDatabaseForm() Form {
return Form{
Name: "database_properties",
Label: "Database Properties",
Description: "Connection details for the backing database for the service broker.",
Properties: []FormProperty{
{Name: "db_host", Type: "string", Label: "Database host", Configurable: true},
{Name: "db_username", Type: "string", Label: "Database username", Optional: true, Configurable: true},
{Name: "db_password", Type: "secret", Label: "Database password", Optional: true, Configurable: true},
{Name: "db_port", Type: "string", Label: "Database port (defaults to 3306)", Default: "3306", Configurable: true},
{Name: "db_name", Type: "string", Label: "Database name", Default: "servicebroker", Configurable: true},
{Name: "ca_cert", Type: "text", Label: "Server CA cert", Optional: true, Configurable: true},
{Name: "client_cert", Type: "text", Label: "Client cert", Optional: true, Configurable: true},
{Name: "client_key", Type: "text", Label: "Client key", Optional: true, Configurable: true},
},
}
}
// generateServiceAccountForm generates the form for configuring the service
// account.
func generateServiceAccountForm() Form {
return Form{
Name: "root_service_account",
Label: "Root Service Account",
Description: "Please paste in the contents of the json keyfile (un-encoded) for your service account with owner credentials.",
Properties: []FormProperty{
{Name: "root_service_account_json", Type: "text", Label: "Root Service Account JSON", Configurable: true},
},
}
}
func generateFeatureFlagForm() Form {
var formEntries []FormProperty
for _, toggle := range toggles.Features.Toggles() {
toggleEntry := FormProperty{
Name: strings.ToLower(toggle.EnvironmentVariable()),
Type: "boolean",
Label: toggle.Name,
Configurable: true,
Default: fmt.Sprintf("%v", toggle.Default), // the tile deals with all values as strings so a default string is acceptable.
Description: singleLine(toggle.Description),
}
formEntries = append(formEntries, toggleEntry)
}
return Form{
Name: "features",
Label: "Feature Flags",
Description: "Service broker feature flags.",
Properties: formEntries,
}
}
// generateServicePlanForms generates customized service plan forms for all
// registered services that have the ability to customize their variables.
func generateServicePlanForms() []Form {
builtinServices := builtin.BuiltinBrokerRegistry()
out := []Form{}
for _, svc := range builtinServices.GetAllServices() {
planVars := svc.PlanVariables
if planVars == nil || len(planVars) == 0 {
continue
}
form, err := generateServicePlanForm(svc)
if err != nil {
log.Fatalf("Error generating form for %+v, %s", form, err)
}
out = append(out, form)
}
return out
}
// generateServicePlanForm creates a form for adding additional service plans
// to the broker for an existing service.
func generateServicePlanForm(svc *broker.ServiceDefinition) (Form, error) {
entry, err := svc.CatalogEntry()
if err != nil {
return Form{}, err
}
displayName := entry.Metadata.DisplayName
planForm := Form{
Name: strings.ToLower(svc.TileUserDefinedPlansVariable()),
Description: fmt.Sprintf("Generate custom plans for %s.", displayName),
Label: fmt.Sprintf("%s Custom Plans", displayName),
Optional: true,
Properties: []FormProperty{
{
Name: "display_name",
Label: "Display Name",
Type: "string",
Description: "Name of the plan to be displayed to users.",
Configurable: true,
},
{
Name: "description",
Label: "Plan description",
Type: "string",
Description: "The description of the plan shown to users.",
Configurable: true,
},
{
Name: "service",
Label: "Service",
Type: "dropdown_select",
Description: "The service this plan is associated with.",
Default: entry.ID,
Optional: false,
Configurable: true,
Options: []FormOption{
{
Name: entry.ID,
Label: displayName,
},
},
},
},
}
// Along with the above three fixed properties, each plan has optional
// additional properties.
for _, v := range svc.PlanVariables {
prop := brokerVariableToFormProperty(v)
planForm.Properties = append(planForm.Properties, prop)
}
return planForm, nil
}
func generateBrokerpakForm() Form {
return Form{
Name: "brokerpaks",
Label: "Brokerpaks",
Description: `Brokerpaks are ways to extend the broker with custom services defined by Terraform templates.
A brokerpak is an archive comprised of a versioned Terraform binary and providers for one or more platform, a manifest, one or more service definitions, and source code.`,
Properties: []FormProperty{
{
Name: "gsb_brokerpak_config",
Type: "text",
Label: "Global Brokerpak Configuration",
Description: "A JSON map of configuration key/value pairs for all brokerpaks. If a variable isn't found in the specific brokerpak's configuration it's looked up here.",
Default: "{}",
Optional: false,
Configurable: true,
},
},
}
}
func brokerpakConfigurationForm() Form {
return Form{
Name: "gsb_brokerpak_sources",
Description: "Configure Brokerpaks",
Label: "Configure Brokerpaks",
Optional: true,
Properties: []FormProperty{
{
Name: "uri",
Label: "Brokerpak URI",
Type: "string",
Description: `The URI to load. Supported protocols are http, https, gs, and git.
Cloud Storage (gs) URIs follow the gs://<bucket>/<path> convention and will be read using the service broker service account.
You can validate the checksum of any file on download by appending a checksum query parameter to the URI in the format type:value.
Valid checksum types are md5, sha1, sha256 and sha512. e.g. gs://foo/bar.brokerpak?checksum=md5:3063a2c62e82ef8614eee6745a7b6b59`,
Optional: false,
Configurable: true,
},
{
Name: "service_prefix",
Label: "Service Prefix",
Type: "string",
Description: "A prefix to prepend to every service name. This will be exact, so you may want to include a trailing dash.",
Optional: true,
Configurable: true,
},
{
Name: "excluded_services",
Label: "Excluded Services",
Type: "text",
Description: "A list of UUIDs of services to exclude, one per line.",
Optional: true,
Configurable: true,
},
{
Name: "config",
Label: "Brokerpak Configuration",
Type: "text",
Description: "A JSON map of configuration key/value pairs for the brokerpak. If a variable isn't found here, it's looked up in the global config.",
Default: "{}",
Configurable: true,
},
{
Name: "notes",
Label: "Notes",
Type: "text",
Description: "A place for your notes, not used by the broker.",
Optional: true,
Configurable: true,
},
},
}
}
func brokerVariableToFormProperty(v broker.BrokerVariable) FormProperty {
formInput := FormProperty{
Name: v.FieldName,
Label: propertyToLabel(v.FieldName),
Type: string(v.Type),
Description: v.Details,
Configurable: true,
Optional: !v.Required,
Default: v.Default,
}
if v.Enum != nil {
formInput.Type = "dropdown_select"
opts := []FormOption{}
for name, label := range v.Enum {
opts = append(opts, FormOption{Name: fmt.Sprintf("%v", name), Label: label})
}
// Sort the options by human-readable label so they end up in a deterministic
// order to prevent odd stuff from coming up during diffs.
sort.Slice(opts, func(i, j int) bool {
return opts[i].Label < opts[j].Label
})
formInput.Options = opts
if len(opts) == 1 {
formInput.Default = opts[0].Name
}
}
return formInput
}
// propertyToLabel converts a JSON snake-case property into a title case
// human-readable alternative.
func propertyToLabel(property string) string {
return strings.Title(strings.NewReplacer("_", " ").Replace(property))
}
func singleLine(text string) string {
lines := strings.Split(text, "\n")
var out []string
for _, line := range lines {
out = append(out, strings.TrimSpace(line))
}
return strings.Join(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/generator/customization-md.go | pkg/generator/customization-md.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 generator
import (
"bytes"
"log"
"strings"
"text/template"
)
const (
formDocumentation = `
# Installation Customization
This file documents the various environment variables you can set to change the functionality of the service broker.
If you are using the PCF Tile deployment, then you can manage all of these options through the operator forms.
If you are running your own, then you can set them in the application manifest of a PCF deployment, or in your pod configuration for Kubernetes.
{{ range $i, $f := .Forms }}{{ template "normalform" $f }}{{ end }}
## Custom Plans
You can specify custom plans for the following services.
The plans MUST be an array of flat JSON objects stored in their associated environment variable e.g. <code>[{...}, {...},...]</code>.
Each plan MUST have a unique UUID, if you modify the plan the UUID should stay the same to ensure previously provisioned services continue to work.
If you are using the Tanzu Operations Manager Tile, it will generate the UUIDs for you.
DO NOT delete plans, instead you should change their labels to mark them as deprecated.
{{ range $i, $f := .ServicePlanForms -}}
{{ template "customplanform" $f }}
{{- end }}
---------------------------------------
_Note: **Do not edit this file**, it was auto-generated by running <code>gcp-service-broker generate customization</code>. If you find an error, change the source code in <tt>customization-md.go</tt> or file a bug._
{{/*=======================================================================*/}}
{{ define "normalform" }}
## {{ .Label }}
{{ .Description }}
You can configure the following environment variables:
| Environment Variable | Type | Description |
|----------------------|------|-------------|
{{ range .Properties -}}
| <tt>{{upper .Name}}</tt>{{ if not .Optional }} <b>*</b>{{end}} | {{ .Type }} | <p>{{ .Label }} {{ .Description }}{{if .Default }} Default: <code>{{ js .Default }}</code>{{- end }}</p>|
{{ end }}
{{ end }}
{{/*=======================================================================*/}}
{{ define "customplanform" -}}
### {{ .Label }}
{{ .Description }}
To specify a custom plan manually, create the plan as JSON in a JSON array and store it in the environment variable: <tt>{{ upper .Name }}</tt>.
For example:
<code>
[{"id":"00000000-0000-0000-0000-000000000000", "name": "custom-plan-1"{{ range .Properties }}, "{{.Name}}": setme{{ end }}},...]
</code>
<table>
<tr>
<th>JSON Property</th>
<th>Type</th>
<th>Label</th>
<th>Details</th>
</tr>
<tr>
<td><tt>id</tt></td>
<td><i>string</i></td>
<td>Plan UUID</td>
<td>
The UUID of the custom plan, use the <tt>uuidgen</tt> CLI command or [uuidgenerator.net](https://www.uuidgenerator.net/) to create one.
<ul><li><b>Required</b></li></ul>
</td>
</tr>
<tr>
<td><tt>name</tt></td>
<td><i>string</i></td>
<td>Plan CLI Name</td>
<td>
The name of the custom plan used to provision it, must be lower-case, start with a letter a-z and contain only letters, numbers and dashes (-).
<ul><li><b>Required</b></li></ul>
</td>
</tr>
{{ range .Properties }}
<tr>
<td><tt>{{ .Name }}</tt></td>
<td><i>{{ .Type }}</i></td>
<td>{{ .Label }}</td>
<td>
{{ .Description }}
{{ template "variable-details-list" . }}
</td>
</tr>
{{ end }}
</table>
{{ end }}
{{/*=======================================================================*/}}
{{ define "variable-details-list"}}
<ul>
<li>{{ if .Optional }}<i>Optional</i>{{ else }}<b>Required</b>{{ end }}</li>
{{- if .Default }}
<li>Default: <code>{{ js .Default }}</code></li>
{{- end }}
{{- if not .Configurable }}
<li>This option _is not_ user configurable. It must be set to the default.</li>
{{- end }}
{{- if .Options }}
<li>Valid Values:
<ul>
{{ range .Options }}<li><tt>{{ .Name }}</tt> - {{ .Label }}</li>{{ end }}
</ul>
</li>
{{- end }}
</ul>
{{ end }}
`
)
var (
customizationTemplateFuncs = template.FuncMap{
"upper": strings.ToUpper,
}
formDocumentationTemplate = template.Must(template.New("name").Funcs(customizationTemplateFuncs).Parse(formDocumentation))
)
func GenerateCustomizationMd() string {
tileForms := GenerateForms()
var buf bytes.Buffer
if err := formDocumentationTemplate.Execute(&buf, tileForms); err != nil {
log.Fatalf("Error rendering template: %s", err)
}
return cleanMdOutput(buf.String())
}
// Remove trailing whitespace from the document and every line
func cleanMdOutput(text string) string {
text = strings.TrimSpace(text)
lines := strings.Split(text, "\n")
for i, l := range lines {
lines[i] = strings.TrimRight(l, " \t")
}
return strings.Join(lines, "\n")
}
| 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/generator/pcf-artifacts.go | pkg/generator/pcf-artifacts.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 generator
import (
"bytes"
"log"
"text/template"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/config/migration"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
)
const (
appName = "gcp-service-broker"
appDescription = "A service broker for Google Cloud services."
stemcellOs = "ubuntu-xenial"
stemcellVersion = "456.104"
buildpack = "go_buildpack"
goPackageName = "github.com/GoogleCloudPlatform/gcp-service-broker"
goVersion = "go1.14"
copyrightHeader = `# Copyright the Service Broker Project Authors. All rights reserved.
#
# 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.
# This file is AUTOGENERATED by ./gcp-service-broker generate, DO NOT EDIT IT.
---`
manifestYmlTemplate = copyrightHeader + `
applications:
- name: {{.appName}}
memory: 1G
buildpack: {{.buildpack}}
env:
GOPACKAGENAME: {{.goPackageName}}
GOVERSION: {{.goVersion}}`
tileYmlTemplate = copyrightHeader + `
name: {{.appName}}
icon_file: gcp_logo.png
label: Google Cloud Platform Service Broker
description: '{{.appDescription}}'
product_version: "{{.appVersion}}"
org: system
stemcell_criteria:
os: '{{.stemcellOs}}'
version: '{{.stemcellVersion}}'
apply_open_security_group: true
migration: |
{{.migrationScript}}
packages:
- name: {{.appName}}
type: app-broker
manifest:
buildpack: {{.buildpack}}
path: /tmp/gcp-service-broker.zip
env:
GOPACKAGENAME: {{.goPackageName}}
GOVERSION: {{.goVersion}}
# You can override plans here.
needs_cf_credentials: true
enable_global_access_to_plans: true
# Uncomment this section if you want to display forms with configurable
# properties in Ops Manager. These properties will be passed to your
# applications as environment variables. You can also refer to them
# elsewhere in this template by using:
# (( .properties.<property-name> ))
`
)
// GenerateManifest creates a manifest.yml from a template.
func GenerateManifest() string {
return runPcfTemplate(manifestYmlTemplate)
}
// GenerateTile creates a tile.yml from a template.
func GenerateTile() string {
return runPcfTemplate(tileYmlTemplate) + GenerateFormsString()
}
func runPcfTemplate(templateString string) string {
migrator := migration.FullMigration()
vars := map[string]interface{}{
"appName": appName,
"appVersion": utils.Version,
"appDescription": appDescription,
"buildpack": buildpack,
"goPackageName": goPackageName,
"goVersion": goVersion,
"stemcellOs": stemcellOs,
"stemcellVersion": stemcellVersion,
"migrationScript": utils.Indent(migrator.TileScript, " "),
}
tmpl, err := template.New("tmpl").Parse(templateString)
if err != nil {
log.Fatalf("parsing: %s", err)
}
// Run the template to verify the output.
var buf bytes.Buffer
err = tmpl.Execute(&buf, vars)
if err != nil {
log.Fatalf("execution: %s", err)
}
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/pkg/varcontext/varcontext.go | pkg/varcontext/varcontext.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 varcontext
import (
"encoding/json"
"fmt"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/hashicorp/go-multierror"
"github.com/spf13/cast"
)
type VarContext struct {
errors *multierror.Error
context map[string]interface{}
}
func (vc *VarContext) validate(key, typeName string, validator func(interface{}) error) {
val, ok := vc.context[key]
if !ok {
vc.errors = multierror.Append(vc.errors, fmt.Errorf("missing value for key %q", key))
return
}
if err := validator(val); err != nil {
vc.errors = multierror.Append(vc.errors, fmt.Errorf("value for %q must be a %s", key, typeName))
}
}
// GetString gets a string from the context, storing an error if the key doesn't
// exist or the variable couldn't be converted to a string.
func (vc *VarContext) GetString(key string) (res string) {
vc.validate(key, "string", func(val interface{}) (err error) {
res, err = cast.ToStringE(val)
return err
})
return
}
// GetInt gets an integer from the context, storing an error if the key doesn't
// exist or the variable couldn't be converted to an int.
func (vc *VarContext) GetInt(key string) (res int) {
vc.validate(key, "integer", func(val interface{}) (err error) {
res, err = cast.ToIntE(val)
return err
})
return
}
// GetBool gets a boolean from the context, storing an error if the key doesn't
// exist or the variable couldn't be converted to a bool.
// Integers can behave like bools in C style, 0 is false.
// The strings "true" and "false" are also cast to their bool values.
func (vc *VarContext) GetBool(key string) (res bool) {
vc.validate(key, "boolean", func(val interface{}) (err error) {
res, err = cast.ToBoolE(val)
return err
})
return
}
// GetStringMapString gets map[string]string from the context,
// storing an error if the key doesn't exist or the variable couldn't be cast.
func (vc *VarContext) GetStringMapString(key string) (res map[string]string) {
vc.validate(key, "map[string]string", func(val interface{}) (err error) {
res, err = cast.ToStringMapStringE(val)
return err
})
return
}
// ToMap gets the underlying map representaiton of the variable context.
func (vc *VarContext) ToMap() map[string]interface{} {
output := make(map[string]interface{})
for k, v := range vc.context {
output[k] = v
}
return output
}
// ToJson gets the underlying JSON representaiton of the variable context.
func (vc *VarContext) ToJson() (json.RawMessage, error) {
return json.Marshal(vc.ToMap())
}
// Error gets the accumulated error(s) that this VarContext holds.
func (vc *VarContext) Error() error {
if vc.errors == nil {
return nil
}
vc.errors.ErrorFormat = utils.SingleLineErrorFormatter
return vc.errors
}
| 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/varcontext/builder.go | pkg/varcontext/builder.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 varcontext
import (
"encoding/json"
"fmt"
"reflect"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext/interpolation"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
multierror "github.com/hashicorp/go-multierror"
"github.com/spf13/cast"
)
const (
TypeObject = "object"
TypeBoolean = "boolean"
TypeArray = "array"
TypeNumber = "number"
TypeString = "string"
TypeInteger = "integer"
)
// ContextBuilder is a builder for VariableContexts.
type ContextBuilder struct {
errors *multierror.Error
context map[string]interface{}
constants map[string]interface{}
}
// Builder creates a new ContextBuilder for constructing VariableContexts.
func Builder() *ContextBuilder {
return &ContextBuilder{
context: make(map[string]interface{}),
constants: make(map[string]interface{}),
}
}
// SetEvalConstants sets constants that will be available to evaluation contexts
// but not in the final output produced by the Build() call.
// These can be used to set values users can't overwrite mistakenly or maliciously.
func (builder *ContextBuilder) SetEvalConstants(constants map[string]interface{}) *ContextBuilder {
builder.constants = constants
return builder
}
// DefaultVariable holds a value that may or may not be evaluated.
// If the value is a string then it will be evaluated.
type DefaultVariable struct {
Name string `json:"name" yaml:"name"`
Default interface{} `json:"default" yaml:"default"`
Overwrite bool `json:"overwrite" yaml:"overwrite"`
Type string `json:"type" yaml:"type"`
}
var _ validation.Validatable = (*DefaultVariable)(nil)
// Validate implements validation.Validatable.
func (dv *DefaultVariable) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(dv.Name, "name"),
validation.ErrIfNil(dv.Default, "default"),
validation.ErrIfNotJSONSchemaType(dv.Type, "type"),
)
}
// MergeDefaults gets the default values from the given BrokerVariables and
// if they're a string, it tries to evaluet it in the built up context.
func (builder *ContextBuilder) MergeDefaults(brokerVariables []DefaultVariable) *ContextBuilder {
for _, v := range brokerVariables {
if v.Default == nil {
continue
}
if _, exists := builder.context[v.Name]; exists && !v.Overwrite {
continue
}
if strVal, ok := v.Default.(string); ok {
builder.MergeEvalResult(v.Name, strVal, v.Type)
} else {
builder.context[v.Name] = v.Default
}
if _, exists := builder.context[v.Name]; exists && !v.Overwrite {
continue
}
}
return builder
}
// MergeEvalResult evaluates the template against the templating engine and
// merges in the value if the result is not an error.
func (builder *ContextBuilder) MergeEvalResult(key, template, resultType string) *ContextBuilder {
evaluationContext := make(map[string]interface{})
for k, v := range builder.context {
evaluationContext[k] = v
}
for k, v := range builder.constants {
evaluationContext[k] = v
}
result, err := interpolation.Eval(template, evaluationContext)
if err != nil {
builder.errors = multierror.Append(fmt.Errorf("couldn't compute the value for %q, template: %q, %v", key, template, err))
return builder
}
converted, err := castTo(result, resultType)
if err != nil {
builder.errors = multierror.Append(err)
return builder
}
builder.context[key] = converted
return builder
}
func toSliceE(value interface{}) ([]interface{}, error) {
kind := reflect.TypeOf(value).Kind()
switch kind {
case reflect.String:
out := []interface{}{}
err := json.Unmarshal([]byte(value.(string)), &out)
return out, err
default:
return cast.ToSliceE(value)
}
}
func castTo(value interface{}, jsonType string) (interface{}, error) {
switch jsonType {
case TypeObject:
return cast.ToStringMapE(value)
case TypeBoolean:
return cast.ToBoolE(value)
case TypeArray:
return toSliceE(value)
case TypeNumber:
return cast.ToFloat64E(value)
case TypeString:
return cast.ToStringE(value)
case TypeInteger:
return cast.ToIntE(value)
case "": // for legacy compatibility
return value, nil
default:
return nil, fmt.Errorf("couldn't cast %v to %s, unknown type", value, jsonType)
}
}
// MergeMap inserts all the keys and values from the map into the context.
func (builder *ContextBuilder) MergeMap(data map[string]interface{}) *ContextBuilder {
for k, v := range data {
builder.context[k] = v
}
return builder
}
// MergeJsonObject converts the raw message to a map[string]interface{} and
// merges the values into the context. Blank RawMessages are treated like
// empty objects.
func (builder *ContextBuilder) MergeJsonObject(data json.RawMessage) *ContextBuilder {
if len(data) == 0 {
return builder
}
out := map[string]interface{}{}
if err := json.Unmarshal(data, &out); err != nil {
builder.errors = multierror.Append(builder.errors, err)
}
builder.MergeMap(out)
return builder
}
// MergeStruct merges the given struct using its JSON field names.
func (builder *ContextBuilder) MergeStruct(data interface{}) *ContextBuilder {
if jo, err := json.Marshal(data); err != nil {
builder.errors = multierror.Append(builder.errors, err)
} else {
builder.MergeJsonObject(jo)
}
return builder
}
// Build generates a finalized VarContext based on the state of the builder.
// Exactly one of VarContext and error will be nil.
func (builder *ContextBuilder) Build() (*VarContext, error) {
if builder.errors != nil {
builder.errors.ErrorFormat = utils.SingleLineErrorFormatter
return nil, builder.errors
}
return &VarContext{context: builder.context}, nil
}
// BuildMap is a shorthand of calling build then turning the returned varcontext
// into a map. Exactly one of map and error will be nil.
func (builder *ContextBuilder) BuildMap() (map[string]interface{}, error) {
vc, err := builder.Build()
if err != nil {
return nil, err
}
return vc.ToMap(), 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/varcontext/varcontext_test.go | pkg/varcontext/varcontext_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 varcontext
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
func TestVarContext_GetString(t *testing.T) {
// The following tests operate on the following example map
testContext := map[string]interface{}{
"anInt": 42,
"aString": "value",
}
tests := map[string]struct {
Key string
Expected string
Error string
}{
"int": {"anInt", "42", ""},
"string": {"aString", "value", ""},
"missing key": {"DNE", "", `missing value for key "DNE"`},
}
for tn, tc := range tests {
t.Run(tn, func(t *testing.T) {
vc := &VarContext{context: testContext}
result := vc.GetString(tc.Key)
if result != tc.Expected {
t.Errorf("Expected to get: %q actual: %q", tc.Expected, result)
}
expectedErrors := tc.Error != ""
hasError := vc.Error() != nil
if hasError != expectedErrors {
t.Error("Got error when not expecting or missing error that was expected")
}
if tc.Error != "" && !strings.Contains(vc.Error().Error(), tc.Error) {
t.Errorf("Expected error to contain %q, but got: %v", tc.Error, vc.Error())
}
})
}
}
func TestVarContext_GetInt(t *testing.T) {
// The following tests operate on the following example map
testContext := map[string]interface{}{
"anInt": 42,
"aString": "value",
}
tests := map[string]struct {
Key string
Expected int
Error string
}{
"int": {"anInt", 42, ""},
"string": {"aString", 0, `value for "aString" must be a integer`},
"missing key": {"DNE", 0, `missing value for key "DNE"`},
}
for tn, tc := range tests {
t.Run(tn, func(t *testing.T) {
vc := &VarContext{context: testContext}
result := vc.GetInt(tc.Key)
if result != tc.Expected {
t.Errorf("Expected to get: %q actual: %q", tc.Expected, result)
}
expectedErrors := tc.Error != ""
hasError := vc.Error() != nil
if hasError != expectedErrors {
t.Errorf("Got error when not expecting or missing error that was expected: %v", vc.Error())
}
if tc.Error != "" && !strings.Contains(vc.Error().Error(), tc.Error) {
t.Errorf("Expected error to contain %q, but got: %v", tc.Error, vc.Error())
}
})
}
}
func TestVarContext_GetBool(t *testing.T) {
// The following tests operate on the following example map
testContext := map[string]interface{}{
"anInt": 42,
"zero": 0,
"tsBool": "true",
"fsBool": "false",
"tBool": true,
"fBool": false,
"aString": "value",
}
tests := map[string]struct {
Key string
Expected bool
Error string
}{
"true bool": {"tBool", true, ""},
"false bool": {"fBool", false, ""},
"true string bool": {"tsBool", true, ""},
"false string bool": {"fsBool", false, ""},
"int": {"anInt", true, ""},
"zero": {"zero", false, ""},
"string": {"aString", false, `value for "aString" must be a boolean`},
"missing key": {"DNE", false, `missing value for key "DNE"`},
}
for tn, tc := range tests {
t.Run(tn, func(t *testing.T) {
vc := &VarContext{context: testContext}
result := vc.GetBool(tc.Key)
if result != tc.Expected {
t.Errorf("Expected to get: %v actual: %v", tc.Expected, result)
}
expectedErrors := tc.Error != ""
hasError := vc.Error() != nil
if hasError != expectedErrors {
t.Errorf("Got error when not expecting or missing error that was expected: %v", vc.Error())
}
if tc.Error != "" && !strings.Contains(vc.Error().Error(), tc.Error) {
t.Errorf("Expected error to contain %q, but got: %v", tc.Error, vc.Error())
}
})
}
}
func TestVarContext_GetStringMapString(t *testing.T) {
// The following tests operate on the following example map
testContext := map[string]interface{}{
"single": map[string]string{"foo": "bar"},
"aString": "value",
"json": `{"foo":"bar"}`,
}
tests := map[string]struct {
Key string
Expected map[string]string
Error string
}{
"single map": {"single", map[string]string{"foo": "bar"}, ""},
"json map": {"json", map[string]string{"foo": "bar"}, ""},
"string": {"aString", map[string]string{}, `value for "aString" must be a map[string]string`},
}
for tn, tc := range tests {
t.Run(tn, func(t *testing.T) {
vc := &VarContext{context: testContext}
result := vc.GetStringMapString(tc.Key)
if !reflect.DeepEqual(result, tc.Expected) {
t.Errorf("Expected to get: %v actual: %v", tc.Expected, result)
}
expectedErrors := tc.Error != ""
hasError := vc.Error() != nil
if hasError != expectedErrors {
t.Fatalf("Got error when not expecting or missing error that was expected: %v", vc.Error())
}
if tc.Error != "" && !strings.Contains(vc.Error().Error(), tc.Error) {
t.Errorf("Expected error to contain %q, but got: %v", tc.Error, vc.Error())
}
})
}
}
func TestVarContext_ToJson(t *testing.T) {
vc := &VarContext{context: map[string]interface{}{
"t": true,
"f": false,
"s": "a string",
"a": []interface{}{"an", "array"},
"F": 123.45,
}}
expected := vc.ToMap()
serialized, _ := vc.ToJson()
actual := make(map[string]interface{})
json.Unmarshal(serialized, &actual)
if !reflect.DeepEqual(expected, actual) {
t.Fatalf("Expected: %#v, Got: %#v", 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/varcontext/builder_test.go | pkg/varcontext/builder_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 varcontext
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
func TestContextBuilder(t *testing.T) {
cases := map[string]struct {
Builder *ContextBuilder
Expected map[string]interface{}
ErrContains string
}{
"an empty context": {
Builder: Builder(),
Expected: map[string]interface{}{},
ErrContains: "",
},
// MergeMap
"MergeMap blank okay": {
Builder: Builder().MergeMap(map[string]interface{}{}),
Expected: map[string]interface{}{},
},
"MergeMap multi-key": {
Builder: Builder().MergeMap(map[string]interface{}{"a": "a", "b": "b"}),
Expected: map[string]interface{}{"a": "a", "b": "b"},
},
"MergeMap overwrite": {
Builder: Builder().MergeMap(map[string]interface{}{"a": "a"}).MergeMap(map[string]interface{}{"a": "aaa"}),
Expected: map[string]interface{}{"a": "aaa"},
},
// MergeDefaults
"MergeDefaults no defaults": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "foo"}}),
Expected: map[string]interface{}{},
},
"MergeDefaults non-string": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "h2g2", Default: 42}}),
Expected: map[string]interface{}{"h2g2": 42},
},
"MergeDefaults basic-string": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "a", Default: "no-template"}}),
Expected: map[string]interface{}{"a": "no-template"},
},
"MergeDefaults template string": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "a", Default: "a"}, {Name: "b", Default: "${a}"}}),
Expected: map[string]interface{}{"a": "a", "b": "a"},
},
"MergeDefaults no-overwrite": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "a", Default: "a"}, {Name: "a", Default: "b", Overwrite: false}}),
Expected: map[string]interface{}{"a": "a"},
},
"MergeDefaults overwrite": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "a", Default: "a"}, {Name: "a", Default: "b", Overwrite: true}}),
Expected: map[string]interface{}{"a": "b"},
},
"MergeDefaults object": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "o", Default: `{"foo": "bar"}`, Type: "object"}}),
Expected: map[string]interface{}{"o": map[string]interface{}{"foo": "bar"}},
},
"MergeDefaults boolean": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "b", Default: `true`, Type: "boolean"}}),
Expected: map[string]interface{}{"b": true},
},
"MergeDefaults array": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "a", Default: `["a","b","c","d"]`, Type: "array"}}),
Expected: map[string]interface{}{"a": []interface{}{"a", "b", "c", "d"}},
},
"MergeDefaults number": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "n", Default: `1.234`, Type: "number"}}),
Expected: map[string]interface{}{"n": 1.234},
},
"MergeDefaults integer": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "i", Default: `1234`, Type: "integer"}}),
Expected: map[string]interface{}{"i": 1234},
},
"MergeDefaults string": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "s", Default: `1234`, Type: "string"}}),
Expected: map[string]interface{}{"s": "1234"},
},
"MergeDefaults blank type": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "s", Default: `1234`, Type: ""}}),
Expected: map[string]interface{}{"s": "1234"},
},
"MergeDefaults bad type": {
Builder: Builder().MergeDefaults([]DefaultVariable{{Name: "s", Default: `1234`, Type: "class"}}),
ErrContains: "couldn't cast 1234 to class, unknown type",
},
// MergeEvalResult
"MergeEvalResult accumulates context": {
Builder: Builder().MergeEvalResult("a", "a", "string").MergeEvalResult("b", "${a}", "string"),
Expected: map[string]interface{}{"a": "a", "b": "a"},
},
"MergeEvalResult errors": {
Builder: Builder().MergeEvalResult("a", "${dne}", "string"),
ErrContains: `couldn't compute the value for "a"`,
},
// MergeJsonObject
"MergeJsonObject blank message": {
Builder: Builder().MergeJsonObject(json.RawMessage{}),
Expected: map[string]interface{}{},
},
"MergeJsonObject valid message": {
Builder: Builder().MergeJsonObject(json.RawMessage(`{"a":"a"}`)),
Expected: map[string]interface{}{"a": "a"},
},
"MergeJsonObject invalid message": {
Builder: Builder().MergeJsonObject(json.RawMessage(`{{{}}}`)),
ErrContains: "invalid character '{'",
},
// MergeStruct
"MergeStruct without JSON Tags": {
Builder: Builder().MergeStruct(struct{ Name string }{Name: "Foo"}),
Expected: map[string]interface{}{"Name": "Foo"},
},
"MergeStruct with JSON Tags": {
Builder: Builder().MergeStruct(struct {
Name string `json:"username"`
}{Name: "Foo"}),
Expected: map[string]interface{}{"username": "Foo"},
},
// constants
"Basic constants": {
Builder: Builder().
SetEvalConstants(map[string]interface{}{"PI": 3.14}).
MergeEvalResult("out", "${PI}", "string"),
Expected: map[string]interface{}{"out": "3.14"},
},
"User overrides constant": {
Builder: Builder().
SetEvalConstants(map[string]interface{}{"PI": 3.14}).
MergeMap(map[string]interface{}{"PI": 3.2}). // reassign incorrectly, https://en.wikipedia.org/wiki/Indiana_Pi_Bill
MergeEvalResult("PI", "${PI}", "string"), // test which PI gets referenced
Expected: map[string]interface{}{"PI": "3.14"},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
vc, err := tc.Builder.Build()
switch {
case err == nil && tc.ErrContains == "":
break
case err == nil && tc.ErrContains != "":
t.Fatalf("Got no error when %q was expected", tc.ErrContains)
case err != nil && tc.ErrContains == "":
t.Fatalf("Got error %v when none was expected", err)
case !strings.Contains(err.Error(), tc.ErrContains):
t.Fatalf("Got error %v, but expected it to contain %q", err, tc.ErrContains)
}
if vc == nil && tc.Expected != nil {
t.Fatalf("Expected: %v, got: %v", tc.Expected, vc)
}
if vc != nil && !reflect.DeepEqual(vc.ToMap(), tc.Expected) {
t.Errorf("Expected: %#v, got: %#v", tc.Expected, vc.ToMap())
}
})
}
}
func ExampleContextBuilder_BuildMap() {
_, e := Builder().MergeEvalResult("a", "${assert(false, \"failure!\")}", "string").BuildMap()
fmt.Printf("Error: %v\n", e)
m, _ := Builder().MergeEvalResult("a", "${1+1}", "string").BuildMap()
fmt.Printf("Map: %v\n", m)
//Output: Error: 1 error(s) occurred: couldn't compute the value for "a", template: "${assert(false, \"failure!\")}", assert: Assertion failed: failure!
// Map: map[a:2]
}
func TestDefaultVariable_Validate(t *testing.T) {
cases := map[string]validation.ValidatableTest{
"empty": validation.ValidatableTest{
Object: &DefaultVariable{},
Expect: errors.New("missing field(s): default, name"),
},
"bad type": validation.ValidatableTest{
Object: &DefaultVariable{
Name: "my-name",
Default: 123,
Type: "stringss",
},
Expect: errors.New("field must match '^(|object|boolean|array|number|string|integer)$': type"),
},
"good": validation.ValidatableTest{
Object: &DefaultVariable{
Name: "my-name",
Default: 123,
Type: "string",
},
Expect: nil,
},
}
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/varcontext/interpolation/eval.go | pkg/varcontext/interpolation/eval.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 interpolation
import (
"reflect"
"github.com/hashicorp/hil"
"github.com/hashicorp/hil/ast"
)
// Eval evaluates the tempate string using hil https://github.com/hashicorp/hil
// with the given variables that can be accessed form the string.
func Eval(templateString string, variables map[string]interface{}) (interface{}, error) {
tree, err := hil.Parse(templateString)
if err != nil {
return nil, err
}
varMap := make(map[string]ast.Variable)
for vn, vv := range variables {
converted, err := hil.InterfaceToVariable(vv)
if err != nil {
return nil, err
}
varMap[vn] = converted
}
config := &hil.EvalConfig{
GlobalScope: &ast.BasicScope{
VarMap: varMap,
FuncMap: hilStandardLibrary,
},
}
result, err := hil.Eval(tree, config)
if err != nil {
return nil, err
}
return result.Value, err
}
// IsHILExpression returns true if the template is a HIL expression and false
// otherwise.
func IsHILExpression(template string) bool {
tree, err := hil.Parse(template)
if err != nil {
return false
}
// Eval will error if it can't resolve a reference so we know the template is
// a HIL expression
result, err := hil.Eval(tree, &hil.EvalConfig{GlobalScope: &ast.BasicScope{}})
if err != nil {
return true
}
// if the template doesn't match the result value then we know something was
// evaluated
return !reflect.DeepEqual(template, result.Value)
}
| 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/varcontext/interpolation/funcs.go | pkg/varcontext/interpolation/funcs.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 interpolation
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"regexp"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/hashicorp/hil"
"github.com/hashicorp/hil/ast"
"github.com/spf13/cast"
)
var hilStandardLibrary = createStandardLibrary()
// createStandardLibrary instantiates all the functions and associates them
// to their names in a lookup table for our standard library.
func createStandardLibrary() map[string]ast.Function {
return map[string]ast.Function{
"time.nano": hilFuncTimeNano(),
"str.truncate": hilFuncStrTruncate(),
"str.queryEscape": hilFuncStrQueryEscape(),
"regexp.matches": hilFuncRegexpMatches(),
"counter.next": hilFuncCounterNext(),
"rand.base64": hilFuncRandBase64(),
"assert": hilFuncAssert(),
"json.marshal": hilFuncJSONMarshal(),
"map.flatten": hilFuncMapFlatten(),
}
}
// hilFuncTimeNano creates a function that returns the current UNIX timestamp
// in nanoseconds as a string. time.nano() -> "1538770941497"
func hilFuncTimeNano() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
return fmt.Sprintf("%d", time.Now().UnixNano()), nil
},
}
}
// hilFuncStrTruncate creates a hil function that truncates a string to a given
// length. str.truncate(3, "hello") -> "hel"
func hilFuncStrTruncate() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeInt, ast.TypeString},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
maxLength := args[0].(int)
str := args[1].(string)
if len(str) > maxLength {
return str[:maxLength], nil
}
return str, nil
},
}
}
// hilfuncRegexpMatches creates a hil function that checks if a string matches a given
// regular expression. regexp.matches("^d[0-9]+$", "d2)
func hilFuncRegexpMatches() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeString, ast.TypeString},
ReturnType: ast.TypeBool,
Callback: func(args []interface{}) (interface{}, error) {
return regexp.MatchString(args[0].(string), args[1].(string))
},
}
}
// hilFuncCounterNext creates the hil function counter.next() which
// increments a counter and returns the incremented value.
// The counter is bound to the function definition, so multiple calls to
// this method will create different counters.
func hilFuncCounterNext() ast.Function {
var counter int32
return ast.Function{
ArgTypes: []ast.Type{},
ReturnType: ast.TypeInt,
Callback: func(args []interface{}) (interface{}, error) {
return cast.ToIntE(atomic.AddInt32(&counter, 1))
},
}
}
// hilFuncRandBase64 creates n cryptographically-secure random bytes and
// converts them to Base64 rand.base64(10) -> "YWJjZGVmZ2hpag==".
func hilFuncRandBase64() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeInt},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
passwordLength := args[0].(int)
rb := make([]byte, passwordLength)
if _, err := rand.Read(rb); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(rb), nil
},
}
}
// hilFuncStrQueryEscape escapes a string suitable for embedding in a URL.
func hilFuncStrQueryEscape() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeString},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
return url.QueryEscape(args[0].(string)), nil
},
}
}
// hilFuncAssert throws an error with the second param if the first param is falsy.
func hilFuncAssert() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeBool, ast.TypeString},
ReturnType: ast.TypeBool,
Callback: func(args []interface{}) (interface{}, error) {
condition := args[0].(bool)
message := args[1].(string)
if !condition {
return false, fmt.Errorf("Assertion failed: %s", message)
}
return true, nil
},
}
}
// hilFuncJSONMarshal marshals a value as JSON.
func hilFuncJSONMarshal() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeAny},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
unwrapped, err := hilToInterface(args[0])
if err != nil {
return nil, err
}
bytes, err := json.Marshal(unwrapped)
if err != nil {
return nil, fmt.Errorf("couldn't convert: %v to JSON %s", args[0], err)
}
return string(bytes), nil
},
}
}
// hilFuncMapFlatten flattens a map into a string of key/value pairs with
// given separators.
func hilFuncMapFlatten() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeString, ast.TypeString, ast.TypeMap},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
kvSep := args[0].(string)
tupleSep := args[1].(string)
unwrapped, err := hilToInterface(args[2])
if err != nil {
return nil, err
}
outArr := []string{}
for k, v := range unwrapped.(map[string]interface{}) {
outArr = append(outArr, fmt.Sprintf("%v%s%v", k, kvSep, v))
}
sort.Strings(outArr)
return strings.Join(outArr, tupleSep), nil
},
}
}
func hilToInterface(arg interface{}) (interface{}, error) {
// The types here cover what HIL supports.
switch arg.(type) {
case map[string]ast.Variable:
out := make(map[string]interface{})
for key, v := range arg.(map[string]ast.Variable) {
val, verr := hilToInterface(v)
if verr != nil {
return nil, verr
}
out[key] = val
}
return out, nil
case []ast.Variable:
var out []interface{}
for _, v := range arg.([]ast.Variable) {
unwrapped, err := hil.VariableToInterface(v)
if err != nil {
return nil, err
}
out = append(out, unwrapped)
}
return out, nil
case ast.Variable:
return hil.VariableToInterface(arg.(ast.Variable))
default:
return arg, 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/varcontext/interpolation/eval_test.go | pkg/varcontext/interpolation/eval_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 interpolation
import (
"reflect"
"strings"
"testing"
"time"
"github.com/hashicorp/hil"
"github.com/spf13/cast"
)
func TestEval(t *testing.T) {
tests := map[string]struct {
Template string
Variables map[string]interface{}
Expected interface{}
ErrorContains string
}{
"Non-Templated String": {Template: "foo", Expected: "foo"},
"Basic Evaluation": {Template: "${33}", Expected: "33"},
"Escaped Evaluation": {Template: "$${33}", Expected: "${33}"},
"Missing Variable": {Template: "${a}", ErrorContains: "unknown variable accessed: a"},
"Variable Substitution": {Template: "${foo}", Variables: map[string]interface{}{"foo": 33}, Expected: "33"},
"Bad Template": {Template: "${", ErrorContains: "expected expression"},
"Truncate Required": {Template: `${str.truncate(2, "expression")}`, Expected: "ex"},
"Truncate Not Required": {Template: `${str.truncate(200, "expression")}`, Expected: "expression"},
"Counter": {Template: "${counter.next()},${counter.next()},${counter.next()}", Expected: "1,2,3"},
"Query Escape": {Template: `${str.queryEscape("hello world")}`, Expected: "hello+world"},
"Query Amp": {Template: `${str.queryEscape("hello&world")}`, Expected: "hello%26world"},
"Regex": {Template: `${regexp.matches("^(D|d)[0-9]+$", "d12345")}`, Expected: "true"},
"Bad Regex": {Template: `${regexp.matches("^($", "d12345")}`, ErrorContains: "error parsing regexp"},
"Conditionals True": {Template: `${true ? "foo" : "bar"}`, Expected: "foo"},
"Conditionals False": {Template: `${false ? "foo" : "bar"}`, Expected: "bar"},
"No Short Circuit": {Template: `${false ? counter.next() : counter.next()}`, Expected: "2"},
"assert success": {Template: `${assert(true, "nothing should happen")}`, Expected: "true"},
"assert failure": {Template: `${assert(false, "failure message")}`, ErrorContains: "failure message"},
"assert message": {Template: `${assert(false, "failure message ${1+1}")}`, ErrorContains: "failure message 2"},
"json marshal": {Template: "${json.marshal(mapval)}", Variables: map[string]interface{}{"mapval": map[string]string{"hello": "world"}}, Expected: `{"hello":"world"}`},
"json marshal array": {Template: "${json.marshal(list)}", Variables: map[string]interface{}{"list": []string{"a", "b", "c"}}, Expected: `["a","b","c"]`},
"json marshal numeric": {Template: "${json.marshal(42)}", Expected: `42`},
"json marshal string": {Template: `${json.marshal("str")}`, Expected: `"str"`},
"json marshal true": {Template: "${json.marshal(true)}", Expected: `true`},
"json marshal false": {Template: "${json.marshal(false)}", Expected: `false`},
"map flatten blank": {Template: `${map.flatten(":", ";", mapval)}`, Variables: map[string]interface{}{"mapval": map[string]string{}}, Expected: ``},
"map flatten one": {Template: `${map.flatten(":", ";", mapval)}`, Variables: map[string]interface{}{"mapval": map[string]string{"key1": "val1"}}, Expected: `key1:val1`},
"map flatten": {Template: `${map.flatten(":", ";", mapval)}`, Variables: map[string]interface{}{"mapval": map[string]string{"key1": "val1", "key2": "val2"}}, Expected: `key1:val1;key2:val2`},
}
for tn, tc := range tests {
hilStandardLibrary = createStandardLibrary()
t.Run(tn, func(t *testing.T) {
res, err := Eval(tc.Template, tc.Variables)
expectingErr := tc.ErrorContains != ""
hasErr := err != nil
if expectingErr != hasErr {
t.Errorf("Expecting error? %v, got: %v", expectingErr, err)
}
if expectingErr && !strings.Contains(err.Error(), tc.ErrorContains) {
t.Errorf("Expected error: %v to contain %q", err, tc.ErrorContains)
}
if !reflect.DeepEqual(tc.Expected, res) {
t.Errorf("Expected result: %+v, got %+v", tc.Expected, res)
}
})
}
}
func TestHilFuncTimeNano(t *testing.T) {
before := time.Now().UnixNano()
result, _ := Eval("${time.nano()}", nil)
value := cast.ToInt64(result)
after := time.Now().UnixNano()
if before >= value || value >= after {
t.Errorf("Expected %d < %d < %d", before, value, after)
}
}
func TestHilFuncRandBase64(t *testing.T) {
result, _ := Eval("${rand.base64(32)}", nil)
length := len(result.(string))
if length != 44 {
t.Errorf("Expected length to be %d got %d", 44, length)
}
result, _ = Eval("${rand.base64(16)}", nil)
length = len(result.(string))
if length != 24 {
t.Errorf("Expected length to be %d got %d", 44, length)
}
}
func TestHilToInterface(t *testing.T) {
// This function tests hilToInterface operates correctly with regards to
// taking valid user inputs (i.e. only JSON values), converting them to HIL
// values then converting them back.
tests := map[string]struct {
UserInput interface{}
Expected interface{}
}{
"string": {UserInput: "foo", Expected: "foo"},
"numeric": {UserInput: 42, Expected: "42"},
"bool-true": {UserInput: true, Expected: "1"},
"bool-false": {UserInput: false, Expected: "0"},
"str-array": {UserInput: []interface{}{"a", "b"}, Expected: []interface{}{"a", "b"}},
"mixed-array": {UserInput: []interface{}{"a", 2}, Expected: []interface{}{"a", "2"}},
"object": {
UserInput: map[string]interface{}{"s": "str", "n": 42.0, "a": []interface{}{"a", 2}},
Expected: map[string]interface{}{"s": "str", "n": "42", "a": []interface{}{"a", "2"}},
},
}
for tn, tc := range tests {
t.Run(tn, func(t *testing.T) {
converted, err := hil.InterfaceToVariable(tc.UserInput)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
res, err := hilToInterface(converted)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if !reflect.DeepEqual(tc.Expected, res) {
t.Errorf("Expected result: %+v (%t), got %+v (%t)", tc.Expected, tc.Expected, res, res)
}
})
}
}
func TestIsHILExpression(t *testing.T) {
cases := map[string]struct {
expr string
expected bool
}{
"plain string": {expr: "abcd", expected: false},
"bad expression": {expr: "${", expected: false},
"expression": {expr: "${time.now()}", expected: true},
"constant": {expr: `${"abcd"}`, expected: true},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := IsHILExpression(tc.expr)
if actual != tc.expected {
t.Errorf("Expected result: %+v got %+v for %v", tc.expected, actual, tc.expr)
}
})
}
}
| 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/providers/tf/job_runner.go | pkg/providers/tf/job_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 tf
import (
"context"
"errors"
"fmt"
"time"
"code.cloudfoundry.org/lager"
"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/wrapper"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
)
const (
InProgress = "in progress"
Succeeded = "succeeded"
Failed = "failed"
)
// NewTfJobRunerFromEnv creates a new TfJobRunner with default configuration values.
func NewTfJobRunerFromEnv() (*TfJobRunner, error) {
projectId, err := utils.GetDefaultProjectId()
if err != nil {
return nil, err
}
return NewTfJobRunnerForProject(projectId), nil
}
// Construct a new JobRunner for the given project.
func NewTfJobRunnerForProject(projectId string) *TfJobRunner {
return &TfJobRunner{
ProjectId: projectId,
ServiceAccount: utils.GetServiceAccountJson(),
}
}
// TfJobRunner is responsible for executing terraform jobs in the background and
// providing a way to log and access the state of those background tasks.
//
// Jobs are given an ID and a workspace to operate in, and then the TfJobRunner
// is told which Terraform commands to execute on the given job.
// The TfJobRunner executes those commands in the background and keeps track of
// their state in a database table which gets updated once the task is completed.
//
// The TfJobRunner keeps track of the workspace and the Terraform state file so
// subsequent commands will operate on the same structure.
type TfJobRunner struct {
ProjectId string
ServiceAccount string
// Executor holds a custom executor that will be called when commands are run.
Executor wrapper.TerraformExecutor
}
// StageJob stages a job to be executed. Before the workspace is saved to the
// database, the modules and inputs are validated by Terraform.
func (runner *TfJobRunner) StageJob(ctx context.Context, jobId string, workspace *wrapper.TerraformWorkspace) error {
workspace.Executor = runner.Executor
// Validate that TF is happy with the workspace
if err := workspace.Validate(); err != nil {
return err
}
workspaceString, err := workspace.Serialize()
if err != nil {
return err
}
deployment := &models.TerraformDeployment{
ID: jobId,
Workspace: workspaceString,
LastOperationType: "validation",
}
return runner.operationFinished(nil, workspace, deployment)
}
func (runner *TfJobRunner) markJobStarted(ctx context.Context, deployment *models.TerraformDeployment, operationType string) error {
// update the deployment info
deployment.LastOperationType = operationType
deployment.LastOperationState = InProgress
deployment.LastOperationMessage = ""
if err := db_service.SaveTerraformDeployment(ctx, deployment); err != nil {
return err
}
return nil
}
func (runner *TfJobRunner) hydrateWorkspace(ctx context.Context, deployment *models.TerraformDeployment) (*wrapper.TerraformWorkspace, error) {
ws, err := wrapper.DeserializeWorkspace(deployment.Workspace)
if err != nil {
return nil, err
}
// TODO(josephlewis42) don't assume every pak needs Google specific creds
// GOOGLE_CREDENTIALS needs to be set to the JSON key and GOOGLE_PROJECT
// needs to be set to the project
env := map[string]string{
"GOOGLE_CREDENTIALS": runner.ServiceAccount,
"GOOGLE_PROJECT": runner.ProjectId,
}
ws.Executor = wrapper.CustomEnvironmentExecutor(env, runner.Executor)
logger := utils.NewLogger("job-runner")
logger.Info("wrapping", lager.Data{
"wrapper": ws,
})
return ws, nil
}
// Create runs `terraform apply` on the given workspace in the background.
// The status of the job can be found by polling the Status function.
func (runner *TfJobRunner) Create(ctx context.Context, id string) error {
deployment, err := db_service.GetTerraformDeploymentById(ctx, id)
if err != nil {
return err
}
workspace, err := runner.hydrateWorkspace(ctx, deployment)
if err != nil {
return err
}
if err := runner.markJobStarted(ctx, deployment, models.ProvisionOperationType); err != nil {
return err
}
go func() {
err := workspace.Apply()
runner.operationFinished(err, workspace, deployment)
}()
return nil
}
// Destroy runs `terraform destroy` on the given workspace in the background.
// The status of the job can be found by polling the Status function.
func (runner *TfJobRunner) Destroy(ctx context.Context, id string) error {
deployment, err := db_service.GetTerraformDeploymentById(ctx, id)
if err != nil {
return err
}
workspace, err := runner.hydrateWorkspace(ctx, deployment)
if err != nil {
return err
}
if err := runner.markJobStarted(ctx, deployment, models.DeprovisionOperationType); err != nil {
return err
}
go func() {
err := workspace.Destroy()
runner.operationFinished(err, workspace, deployment)
}()
return nil
}
// operationFinished closes out the state of the background job so clients that
// are polling can get the results.
func (runner *TfJobRunner) operationFinished(err error, workspace *wrapper.TerraformWorkspace, deployment *models.TerraformDeployment) error {
if err == nil {
deployment.LastOperationState = Succeeded
deployment.LastOperationMessage = ""
} else {
deployment.LastOperationState = Failed
deployment.LastOperationMessage = err.Error()
}
workspaceString, err := workspace.Serialize()
if err != nil {
deployment.LastOperationState = Failed
deployment.LastOperationMessage = fmt.Sprintf("couldn't serialize workspace, contact your operator for cleanup: %s", err.Error())
}
deployment.Workspace = workspaceString
return db_service.SaveTerraformDeployment(context.Background(), deployment)
}
// Status gets the status of the most recent job on the workspace.
// If isDone is true, then the status of the operation will not change again.
// if isDone is false, then the operation is ongoing.
func (runner *TfJobRunner) Status(ctx context.Context, id string) (isDone bool, err error) {
deployment, err := db_service.GetTerraformDeploymentById(ctx, id)
if err != nil {
return true, err
}
switch deployment.LastOperationState {
case Succeeded:
return true, nil
case Failed:
return true, errors.New(deployment.LastOperationMessage)
default:
return false, nil
}
}
// Outputs gets the output variables for the given module instance in the workspace.
func (runner *TfJobRunner) Outputs(ctx context.Context, id, instanceName string) (map[string]interface{}, error) {
deployment, err := db_service.GetTerraformDeploymentById(ctx, id)
if err != nil {
return nil, err
}
ws, err := wrapper.DeserializeWorkspace(deployment.Workspace)
if err != nil {
return nil, err
}
return ws.Outputs(instanceName)
}
// Wait waits for an operation to complete, polling its status once per second.
func (runner *TfJobRunner) Wait(ctx context.Context, id string) error {
for {
select {
case <-ctx.Done():
return nil
case <-time.After(1 * time.Second):
isDone, err := runner.Status(ctx, id)
if isDone {
return 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/providers/tf/provider.go | pkg/providers/tf/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 tf
import (
"context"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf/wrapper"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
// NewTerraformProvider creates a new ServiceProvider backed by Terraform module definitions for provision and bind.
func NewTerraformProvider(jobRunner *TfJobRunner, logger lager.Logger, serviceDefinition TfServiceDefinitionV1) broker.ServiceProvider {
return &terraformProvider{
serviceDefinition: serviceDefinition,
jobRunner: jobRunner,
logger: logger.Session("terraform-" + serviceDefinition.Name),
}
}
type terraformProvider struct {
base.MergedInstanceCredsMixin
logger lager.Logger
jobRunner *TfJobRunner
serviceDefinition TfServiceDefinitionV1
}
// Provision creates the necessary resources that an instance of this service
// needs to operate.
func (provider *terraformProvider) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
provider.logger.Info("provision", lager.Data{
"context": provisionContext.ToMap(),
})
tfId, err := provider.create(ctx, provisionContext, provider.serviceDefinition.ProvisionSettings)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
return models.ServiceInstanceDetails{
OperationId: tfId,
OperationType: models.ProvisionOperationType,
}, nil
}
// Bind creates a new backing Terraform job and executes it, waiting on the result.
func (provider *terraformProvider) Bind(ctx context.Context, bindContext *varcontext.VarContext) (map[string]interface{}, error) {
provider.logger.Info("bind", lager.Data{
"context": bindContext.ToMap(),
})
tfId, err := provider.create(ctx, bindContext, provider.serviceDefinition.BindSettings)
if err != nil {
return nil, err
}
if err := provider.jobRunner.Wait(ctx, tfId); err != nil {
return nil, err
}
return provider.jobRunner.Outputs(ctx, tfId, wrapper.DefaultInstanceName)
}
func (provider *terraformProvider) create(ctx context.Context, vars *varcontext.VarContext, action TfServiceDefinitionV1Action) (string, error) {
tfId := vars.GetString("tf_id")
if err := vars.Error(); err != nil {
return "", err
}
workspace, err := wrapper.NewWorkspace(vars.ToMap(), action.Template)
if err != nil {
return tfId, err
}
if err := provider.jobRunner.StageJob(ctx, tfId, workspace); err != nil {
return tfId, err
}
return tfId, provider.jobRunner.Create(ctx, tfId)
}
// Unbind performs a terraform destroy on the binding.
func (provider *terraformProvider) Unbind(ctx context.Context, instanceRecord models.ServiceInstanceDetails, bindRecord models.ServiceBindingCredentials) error {
tfId := generateTfId(instanceRecord.ID, bindRecord.BindingId)
provider.logger.Info("unbind", lager.Data{
"instance": instanceRecord.ID,
"binding": bindRecord.ID,
"tfId": tfId,
})
if err := provider.jobRunner.Destroy(ctx, tfId); err != nil {
return err
}
return provider.jobRunner.Wait(ctx, tfId)
}
// Deprovision performs a terraform destroy on the instance.
func (provider *terraformProvider) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (operationId *string, err error) {
provider.logger.Info("terraform-deprovision", lager.Data{
"instance": instance.ID,
})
tfId := generateTfId(instance.ID, "")
if err := provider.jobRunner.Destroy(ctx, tfId); err != nil {
return nil, err
}
return &tfId, nil
}
// PollInstance returns the instance status of the backing job.
func (provider *terraformProvider) PollInstance(ctx context.Context, instance models.ServiceInstanceDetails) (bool, error) {
return provider.jobRunner.Status(ctx, generateTfId(instance.ID, ""))
}
// ProvisionsAsync is always true for Terraformprovider.
func (provider *terraformProvider) ProvisionsAsync() bool {
return true
}
// DeprovisionsAsync is always true for Terraformprovider.
func (provider *terraformProvider) DeprovisionsAsync() bool {
return true
}
// 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.
func (provider *terraformProvider) UpdateInstanceDetails(ctx context.Context, instance *models.ServiceInstanceDetails) error {
tfId := generateTfId(instance.ID, "")
outs, err := provider.jobRunner.Outputs(ctx, tfId, wrapper.DefaultInstanceName)
if err != nil {
return err
}
return instance.SetOtherDetails(outs)
}
| 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/providers/tf/definition.go | pkg/providers/tf/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 tf
import (
"fmt"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/tf/wrapper"
"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"
"golang.org/x/oauth2/jwt"
)
// TfServiceDefinitionV1 is the first version of user defined services.
type TfServiceDefinitionV1 struct {
Version int `yaml:"version"`
Name string `yaml:"name"`
Id string `yaml:"id"`
Description string `yaml:"description"`
DisplayName string `yaml:"display_name"`
ImageUrl string `yaml:"image_url"`
DocumentationUrl string `yaml:"documentation_url"`
SupportUrl string `yaml:"support_url"`
Tags []string `yaml:"tags,flow"`
Plans []TfServiceDefinitionV1Plan `yaml:"plans"`
ProvisionSettings TfServiceDefinitionV1Action `yaml:"provision"`
BindSettings TfServiceDefinitionV1Action `yaml:"bind"`
Examples []broker.ServiceExample `yaml:"examples"`
// Internal SHOULD be set to true for Google maintained services.
Internal bool `yaml:"-"`
}
// TfServiceDefinitionV1Plan represents a service plan in a human-friendly format
// that can be converted into an OSB compatible plan.
type TfServiceDefinitionV1Plan struct {
Name string `yaml:"name"`
Id string `yaml:"id"`
Description string `yaml:"description"`
DisplayName string `yaml:"display_name"`
Bullets []string `yaml:"bullets,omitempty"`
Free bool `yaml:"free,omitempty"`
Properties map[string]string `yaml:"properties"`
ProvisionOverrides map[string]interface{} `yaml:"provision_overrides,omitempty"`
BindOverrides map[string]interface{} `yaml:"bind_overrides,omitempty"`
}
var _ validation.Validatable = (*TfServiceDefinitionV1Plan)(nil)
// Validate implements validation.Validatable.
func (plan *TfServiceDefinitionV1Plan) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(plan.Name, "name"),
validation.ErrIfNotUUID(plan.Id, "id"),
validation.ErrIfBlank(plan.Description, "description"),
validation.ErrIfBlank(plan.DisplayName, "display_name"),
)
}
// Converts this plan definition to a broker.ServicePlan.
func (plan *TfServiceDefinitionV1Plan) ToPlan() broker.ServicePlan {
masterPlan := brokerapi.ServicePlan{
ID: plan.Id,
Description: plan.Description,
Name: plan.Name,
Free: brokerapi.FreeValue(plan.Free),
Metadata: &brokerapi.ServicePlanMetadata{
Bullets: plan.Bullets,
DisplayName: plan.DisplayName,
},
}
return broker.ServicePlan{
ServicePlan: masterPlan,
ServiceProperties: plan.Properties,
ProvisionOverrides: plan.ProvisionOverrides,
BindOverrides: plan.BindOverrides,
}
}
// TfServiceDefinitionV1Action holds information needed to process user inputs
// for a single provision or bind call.
type TfServiceDefinitionV1Action struct {
PlanInputs []broker.BrokerVariable `yaml:"plan_inputs"`
UserInputs []broker.BrokerVariable `yaml:"user_inputs"`
Computed []varcontext.DefaultVariable `yaml:"computed_inputs"`
Template string `yaml:"template"`
Outputs []broker.BrokerVariable `yaml:"outputs"`
}
var _ validation.Validatable = (*TfServiceDefinitionV1Action)(nil)
// Validate implements validation.Validatable.
func (action *TfServiceDefinitionV1Action) Validate() (errs *validation.FieldError) {
for i, v := range action.PlanInputs {
errs = errs.Also(v.Validate().ViaFieldIndex("plan_inputs", i))
}
for i, v := range action.UserInputs {
errs = errs.Also(v.Validate().ViaFieldIndex("user_inputs", i))
}
for i, v := range action.Computed {
errs = errs.Also(v.Validate().ViaFieldIndex("computed_inputs", i))
}
errs = errs.Also(
validation.ErrIfNotHCL(action.Template, "template"),
action.validateTemplateInputs().ViaField("template"),
action.validateTemplateOutputs().ViaField("template"),
)
for i, v := range action.Outputs {
errs = errs.Also(v.Validate().ViaFieldIndex("outputs", i))
}
return errs
}
func (action *TfServiceDefinitionV1Action) ValidateTemplateIO() (errs *validation.FieldError) {
return errs.Also(
action.validateTemplateInputs().ViaField("template"),
action.validateTemplateOutputs().ViaField("template"),
)
}
// validateTemplateInputs checks that all the inputs of the Terraform template
// are defined by the service.
func (action *TfServiceDefinitionV1Action) validateTemplateInputs() (errs *validation.FieldError) {
inputs := utils.NewStringSet()
for _, in := range action.PlanInputs {
inputs.Add(in.FieldName)
}
for _, in := range action.UserInputs {
inputs.Add(in.FieldName)
}
for _, in := range action.Computed {
inputs.Add(in.Name)
}
tfModule := wrapper.ModuleDefinition{Definition: action.Template}
tfIn, err := tfModule.Inputs()
if err != nil {
return &validation.FieldError{
Message: err.Error(),
}
}
missingFields := utils.NewStringSet(tfIn...).Minus(inputs).ToSlice()
if len(missingFields) > 0 {
return &validation.FieldError{
Message: "fields used but not declared",
Paths: missingFields,
}
}
return nil
}
// validateTemplateOutputs checks that the Terraform template outputs match
// the names of the defined outputs.
func (action *TfServiceDefinitionV1Action) validateTemplateOutputs() (errs *validation.FieldError) {
definedOutputs := utils.NewStringSet()
for _, in := range action.Outputs {
definedOutputs.Add(in.FieldName)
}
tfModule := wrapper.ModuleDefinition{Definition: action.Template}
tfOut, err := tfModule.Outputs()
if err != nil {
return &validation.FieldError{
Message: err.Error(),
}
}
if !definedOutputs.Equals(utils.NewStringSet(tfOut...)) {
return &validation.FieldError{
Message: fmt.Sprintf("template outputs %v must match declared outputs %v", tfOut, definedOutputs),
}
}
return nil
}
var _ validation.Validatable = (*TfServiceDefinitionV1)(nil)
// Validate checks the service definition for semantic errors.
func (tfb *TfServiceDefinitionV1) Validate() (errs *validation.FieldError) {
if tfb.Version != 1 {
errs = errs.Also(validation.ErrInvalidValue(tfb.Version, "version"))
}
errs = errs.Also(
validation.ErrIfBlank(tfb.Name, "name"),
validation.ErrIfNotUUID(tfb.Id, "id"),
validation.ErrIfBlank(tfb.Description, "description"),
validation.ErrIfBlank(tfb.DisplayName, "display_name"),
validation.ErrIfNotURL(tfb.ImageUrl, "image_url"),
validation.ErrIfNotURL(tfb.DocumentationUrl, "documentation_url"),
validation.ErrIfNotURL(tfb.SupportUrl, "support_url"),
)
for i, v := range tfb.Plans {
errs = errs.Also(v.Validate().ViaFieldIndex("plans", i))
}
errs = errs.Also(tfb.ProvisionSettings.Validate().ViaField("provision"))
errs = errs.Also(tfb.BindSettings.Validate().ViaField("bind"))
for i, v := range tfb.Examples {
errs = errs.Also(v.Validate().ViaFieldIndex("examples", i))
}
return errs
}
// ToService converts the flat TfServiceDefinitionV1 into a broker.ServiceDefinition
// that the registry can use.
func (tfb *TfServiceDefinitionV1) ToService(executor wrapper.TerraformExecutor) (*broker.ServiceDefinition, error) {
if err := tfb.Validate(); err != nil {
return nil, err
}
var rawPlans []broker.ServicePlan
for _, plan := range tfb.Plans {
rawPlans = append(rawPlans, plan.ToPlan())
}
// Bindings get special computed properties because the broker didn't
// originally support injecting plan variables into a binding
// to fix that, we auto-inject the properties from the plan to make it look
// like they were to the TF template.
bindComputed := []varcontext.DefaultVariable{}
for _, pi := range tfb.BindSettings.PlanInputs {
bindComputed = append(bindComputed, varcontext.DefaultVariable{
Name: pi.FieldName,
Default: fmt.Sprintf("${request.plan_properties[%q]}", pi.FieldName),
Overwrite: true,
Type: string(pi.Type),
})
}
bindComputed = append(bindComputed, tfb.BindSettings.Computed...)
bindComputed = append(bindComputed, varcontext.DefaultVariable{
Name: "tf_id",
Default: "tf:${request.instance_id}:${request.binding_id}",
Overwrite: true,
})
constDefn := *tfb
return &broker.ServiceDefinition{
Id: tfb.Id,
Name: tfb.Name,
Description: tfb.Description,
Bindable: true,
PlanUpdateable: false,
DisplayName: tfb.DisplayName,
DocumentationUrl: tfb.DocumentationUrl,
SupportUrl: tfb.SupportUrl,
ImageUrl: tfb.ImageUrl,
Tags: tfb.Tags,
Plans: rawPlans,
ProvisionInputVariables: tfb.ProvisionSettings.UserInputs,
ProvisionComputedVariables: append(tfb.ProvisionSettings.Computed, varcontext.DefaultVariable{
Name: "tf_id",
Default: "tf:${request.instance_id}:",
Overwrite: true,
}),
BindInputVariables: tfb.BindSettings.UserInputs,
BindComputedVariables: bindComputed,
BindOutputVariables: append(tfb.ProvisionSettings.Outputs, tfb.BindSettings.Outputs...),
PlanVariables: append(tfb.ProvisionSettings.PlanInputs, tfb.BindSettings.PlanInputs...),
Examples: tfb.Examples,
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
jobRunner := NewTfJobRunnerForProject(projectId)
jobRunner.Executor = executor
return NewTerraformProvider(jobRunner, logger, constDefn)
},
}, nil
}
// generateTfId creates a unique id for a given provision/bind combination that
// will be consistent across calls. This ID will be used in LastOperation polls
// as well as to uniquely identify the workspace.
func generateTfId(instanceId, bindingId string) string {
return fmt.Sprintf("tf:%s:%s", instanceId, bindingId)
}
// NewExampleTfServiceDefinition creates a new service defintition with sample
// values for the service broker suitable to give a user a template to manually
// edit.
func NewExampleTfServiceDefinition() TfServiceDefinitionV1 {
return TfServiceDefinitionV1{
Version: 1,
Name: "example-service",
Id: "00000000-0000-0000-0000-000000000000",
Description: "a longer service description",
DisplayName: "Example Service",
ImageUrl: "https://example.com/icon.jpg",
DocumentationUrl: "https://example.com",
SupportUrl: "https://example.com/support.html",
Tags: []string{"gcp", "example", "service"},
Plans: []TfServiceDefinitionV1Plan{
{
Id: "00000000-0000-0000-0000-000000000001",
Name: "example-email-plan",
DisplayName: "example.com email builder",
Description: "Builds emails for example.com.",
Bullets: []string{"information point 1", "information point 2", "some caveat here"},
Free: false,
Properties: map[string]string{
"domain": "example.com",
"password_special_chars": `@/ \"?`,
},
},
},
ProvisionSettings: TfServiceDefinitionV1Action{
PlanInputs: []broker.BrokerVariable{
{
FieldName: "domain",
Type: broker.JsonTypeString,
Details: "The domain name",
Required: true,
},
},
UserInputs: []broker.BrokerVariable{
{
FieldName: "username",
Type: broker.JsonTypeString,
Details: "The username to create",
Required: true,
},
},
Template: `
variable domain {type = "string"}
variable username {type = "string"}
output email {value = "${var.username}@${var.domain}"}
`,
Outputs: []broker.BrokerVariable{
{
FieldName: "email",
Type: broker.JsonTypeString,
Details: "The combined email address",
Required: true,
},
},
},
BindSettings: TfServiceDefinitionV1Action{
PlanInputs: []broker.BrokerVariable{
{
FieldName: "password_special_chars",
Type: broker.JsonTypeString,
Details: "Supply your own list of special characters to use for string generation.",
Required: true,
},
},
Computed: []varcontext.DefaultVariable{
{Name: "domain", Default: `${request.plan_properties["domain"]}`, Overwrite: true},
{Name: "address", Default: `${instance.details["email"]}`, Overwrite: true},
},
Template: `
variable domain {type = "string"}
variable address {type = "string"}
variable password_special_chars {type = "string"}
resource "random_string" "password" {
length = 16
special = true
override_special = "${var.password_special_chars}"
}
output uri {value = "smtp://${var.address}:${random_string.password.result}@smtp.${var.domain}"}
`,
Outputs: []broker.BrokerVariable{
{
FieldName: "uri",
Type: broker.JsonTypeString,
Details: "The uri to use to connect to this service",
Required: true,
},
},
},
Examples: []broker.ServiceExample{
{
Name: "Example",
Description: "Examples are used for documenting your service AND as integration tests.",
PlanId: "00000000-0000-0000-0000-000000000001",
ProvisionParams: map[string]interface{}{"username": "my-account"},
BindParams: map[string]interface{}{},
},
},
}
}
| 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/providers/tf/definition_test.go | pkg/providers/tf/definition_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 tf
import (
"reflect"
"strings"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
func TestTfServiceDefinitionV1Action_ValidateTemplateIO(t *testing.T) {
cases := map[string]struct {
Action TfServiceDefinitionV1Action
ErrContains string
}{
"nomainal": {
Action: TfServiceDefinitionV1Action{
PlanInputs: []broker.BrokerVariable{{FieldName: "storage_class"}},
UserInputs: []broker.BrokerVariable{{FieldName: "name"}},
Computed: []varcontext.DefaultVariable{{Name: "labels"}},
Template: `
variable storage_class {type = "string"}
variable name {type = "string"}
variable labels {type = "string"}
output bucket_name {value = "${var.name}"}
`,
Outputs: []broker.BrokerVariable{{FieldName: "bucket_name"}},
},
ErrContains: "",
},
"extra inputs okay": {
Action: TfServiceDefinitionV1Action{
PlanInputs: []broker.BrokerVariable{{FieldName: "storage_class"}},
UserInputs: []broker.BrokerVariable{{FieldName: "name"}},
Computed: []varcontext.DefaultVariable{{Name: "labels"}},
Template: `
variable storage_class {type = "string"}
`,
},
ErrContains: "",
},
"missing inputs": {
Action: TfServiceDefinitionV1Action{
PlanInputs: []broker.BrokerVariable{{FieldName: "storage_class"}},
UserInputs: []broker.BrokerVariable{{FieldName: "name"}},
Computed: []varcontext.DefaultVariable{{Name: "labels"}},
Template: `
variable storage_class {type = "string"}
variable not_defined {type = "string"}
`,
},
ErrContains: "fields used but not declared: template.not_defined",
},
"extra template outputs": {
Action: TfServiceDefinitionV1Action{
Template: `
output storage_class {value = "${var.name}"}
output name {value = "${var.name}"}
output labels {value = "${var.name}"}
output bucket_name {value = "${var.name}"}
`,
Outputs: []broker.BrokerVariable{{FieldName: "bucket_name"}},
},
ErrContains: "template outputs [bucket_name labels name storage_class] must match declared outputs [bucket_name]:",
},
"missing template outputs": {
Action: TfServiceDefinitionV1Action{
Template: `
`,
Outputs: []broker.BrokerVariable{{FieldName: "bucket_name"}},
},
ErrContains: "template outputs [] must match declared outputs [bucket_name]:",
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
err := tc.Action.ValidateTemplateIO()
if err == nil {
if tc.ErrContains == "" {
return
}
t.Fatalf("Expected error to contain %q, got: <nil>", tc.ErrContains)
} else {
if tc.ErrContains == "" {
t.Fatalf("Expected no error, got: %v", err)
}
if !strings.Contains(err.Error(), tc.ErrContains) {
t.Fatalf("Expected error to contain %q, got: %v", tc.ErrContains, err)
}
}
})
}
}
func TestNewExampleTfServiceDefinition(t *testing.T) {
example := NewExampleTfServiceDefinition()
if err := example.Validate(); err != nil {
t.Fatalf("example service definition should be valid, but got error: %v", err)
}
}
func TestTfServiceDefinitionV1Plan_ToPlan(t *testing.T) {
cases := map[string]struct {
Definition TfServiceDefinitionV1Plan
Expected broker.ServicePlan
}{
"full": {
Definition: TfServiceDefinitionV1Plan{
Id: "00000000-0000-0000-0000-000000000001",
Name: "example-email-plan",
DisplayName: "example.com email builder",
Description: "Builds emails for example.com.",
Bullets: []string{"information point 1", "information point 2", "some caveat here"},
Free: false,
Properties: map[string]string{
"domain": "example.com",
},
},
Expected: broker.ServicePlan{
ServicePlan: brokerapi.ServicePlan{
ID: "00000000-0000-0000-0000-000000000001",
Name: "example-email-plan",
Description: "Builds emails for example.com.",
Free: brokerapi.FreeValue(false),
Metadata: &brokerapi.ServicePlanMetadata{
Bullets: []string{"information point 1", "information point 2", "some caveat here"},
DisplayName: "example.com email builder",
},
},
ServiceProperties: map[string]string{"domain": "example.com"}},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := tc.Definition.ToPlan()
if !reflect.DeepEqual(actual, tc.Expected) {
t.Fatalf("Expected: %v Actual: %v", tc.Expected, actual)
}
})
}
}
func TestTfServiceDefinitionV1_ToService(t *testing.T) {
definition := TfServiceDefinitionV1{
Version: 1,
Id: "d34705c8-3edf-4ab8-93b3-d97f080da24c",
Name: "my-service-name",
Description: "my-service-description",
DisplayName: "My Service Name",
ImageUrl: "https://example.com/image.png",
SupportUrl: "https://example.com/support",
DocumentationUrl: "https://example.com/docs",
Plans: []TfServiceDefinitionV1Plan{},
ProvisionSettings: TfServiceDefinitionV1Action{
PlanInputs: []broker.BrokerVariable{
{
FieldName: "plan-input-provision",
Type: "string",
Details: "description",
},
},
UserInputs: []broker.BrokerVariable{
{
FieldName: "user-input-provision",
Type: "string",
Details: "description",
},
},
Computed: []varcontext.DefaultVariable{{Name: "computed-input-provision", Default: ""}},
},
BindSettings: TfServiceDefinitionV1Action{
PlanInputs: []broker.BrokerVariable{
{
FieldName: "plan-input-bind",
Type: "integer",
Details: "description",
},
},
UserInputs: []broker.BrokerVariable{
{
FieldName: "user-input-bind",
Type: "string",
Details: "description",
},
},
Computed: []varcontext.DefaultVariable{{Name: "computed-input-bind", Default: ""}},
},
Examples: []broker.ServiceExample{},
}
service, err := definition.ToService(nil)
if err != nil {
t.Fatal(err)
}
expectEqual := func(field string, expected, actual interface{}) {
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected %q to be equal. Expected: %#v, Actual: %#v", field, expected, actual)
}
}
t.Run("basic-info", func(t *testing.T) {
expectEqual("Id", definition.Id, service.Id)
expectEqual("Name", definition.Name, service.Name)
expectEqual("Description", definition.Description, service.Description)
expectEqual("Bindable", true, service.Bindable)
expectEqual("PlanUpdateable", false, service.PlanUpdateable)
expectEqual("DisplayName", definition.DisplayName, service.DisplayName)
expectEqual("DocumentationUrl", definition.DocumentationUrl, service.DocumentationUrl)
expectEqual("SupportUrl", definition.SupportUrl, service.SupportUrl)
expectEqual("ImageUrl", definition.ImageUrl, service.ImageUrl)
expectEqual("Tags", definition.Tags, service.Tags)
})
t.Run("vars", func(t *testing.T) {
expectEqual("ProvisionInputVariables", definition.ProvisionSettings.UserInputs, service.ProvisionInputVariables)
expectEqual("ProvisionComputedVariables", []varcontext.DefaultVariable{
{
Name: "computed-input-provision",
Default: "",
Overwrite: false,
},
{
Name: "tf_id",
Default: "tf:${request.instance_id}:",
Overwrite: true,
},
}, service.ProvisionComputedVariables)
expectEqual("PlanVariables", append(definition.ProvisionSettings.PlanInputs, definition.BindSettings.PlanInputs...), service.PlanVariables)
expectEqual("BindInputVariables", definition.BindSettings.UserInputs, service.BindInputVariables)
expectEqual("BindComputedVariables", []varcontext.DefaultVariable{
{Name: "plan-input-bind", Default: "${request.plan_properties[\"plan-input-bind\"]}", Overwrite: true, Type: "integer"},
{Name: "computed-input-bind", Default: "", Overwrite: false, Type: ""},
{Name: "tf_id", Default: "tf:${request.instance_id}:${request.binding_id}", Overwrite: true, Type: ""},
}, service.BindComputedVariables)
expectEqual("BindOutputVariables", append(definition.ProvisionSettings.Outputs, definition.BindSettings.Outputs...), service.BindOutputVariables)
})
t.Run("examples", func(t *testing.T) {
expectEqual("Examples", definition.Examples, service.Examples)
})
t.Run("provider-builder", func(t *testing.T) {
if service.ProviderBuilder == nil {
t.Fatal("Expected provider builder to not be 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/providers/tf/wrapper/tfstate_test.go | pkg/providers/tf/wrapper/tfstate_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 wrapper
import "fmt"
func ExampleNewTfstate_Good() {
state := `{
"version": 3,
"terraform_version": "0.11.10",
"serial": 2,
"modules": [
{
"path": ["root"],
"outputs": {},
"resources": {},
"depends_on": []
},
{
"path": ["root", "instance"],
"outputs": {},
"resources": {},
"depends_on": []
}
]
}`
_, err := NewTfstate([]byte(state))
fmt.Printf("%v", err)
// Output: <nil>
}
func ExampleNewTfstate_BadVersion() {
state := `{
"version": 4,
"terraform_version": "0.11.10",
"serial": 2,
"modules": [
{
"path": ["root"],
"outputs": {},
"resources": {},
"depends_on": []
}
]
}`
_, err := NewTfstate([]byte(state))
fmt.Printf("%v", err)
// Output: unsupported tfstate version: 4
}
func ExampleTfstate_GetModule() {
state := `{
"version": 3,
"terraform_version": "0.11.10",
"serial": 2,
"modules": [
{
"path": ["root", "instance"],
"outputs": {
"Name": {
"sensitive": false,
"type": "string",
"value": "pcf-binding-ex351277"
}
},
"resources": {},
"depends_on": []
}
]
}`
tfstate, _ := NewTfstate([]byte(state))
fmt.Printf("%v\n", tfstate.GetModule("does-not-exist"))
fmt.Printf("%v\n", tfstate.GetModule("root", "instance"))
// Output: <nil>
// [module: root/instance with 1 outputs]
}
| 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/providers/tf/wrapper/tfstate.go | pkg/providers/tf/wrapper/tfstate.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 wrapper
import (
"encoding/json"
"fmt"
"reflect"
"strings"
)
const (
supportedTfStateVersion = 3
)
// NewTfstate deserializes a tfstate file.
func NewTfstate(stateFile []byte) (*Tfstate, error) {
state := Tfstate{}
if err := json.Unmarshal(stateFile, &state); err != nil {
return nil, err
}
if state.Version != supportedTfStateVersion {
return nil, fmt.Errorf("unsupported tfstate version: %d", state.Version)
}
return &state, nil
}
// Tfstate is a struct that can help us deserialize the tfstate JSON file.
type Tfstate struct {
Version int `json:"version"`
Modules []TfstateModule `json:"modules"`
}
// GetModule gets a module at a given path or nil if none exists for that path.
func (state *Tfstate) GetModule(path ...string) *TfstateModule {
for _, module := range state.Modules {
if reflect.DeepEqual(module.Path, path) {
return &module
}
}
return nil
}
type TfstateModule struct {
Path []string `json:"path"`
Outputs map[string]struct {
Type string `json:"type"`
Value interface{} `json:"value"`
} `json:"outputs"`
}
func (module *TfstateModule) String() string {
path := strings.Join(module.Path, "/")
return fmt.Sprintf("[module: %s with %d outputs]", path, len(module.Outputs))
}
// GetOutputs gets the key/value outputs defined for a module.
func (module *TfstateModule) GetOutputs() map[string]interface{} {
out := make(map[string]interface{})
for outputName, tfOutput := range module.Outputs {
out[outputName] = tfOutput.Value
}
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/providers/tf/wrapper/module_test.go | pkg/providers/tf/wrapper/module_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 wrapper
import (
"fmt"
"strings"
"testing"
)
func ExampleModuleDefinition_Inputs() {
module := ModuleDefinition{
Name: "cloud_storage",
Definition: `
variable name {type = "string"}
variable storage_class {type = "string"}
resource "google_storage_bucket" "bucket" {
name = "${var.name}"
storage_class = "${var.storage_class}"
}
`,
}
inputs, err := module.Inputs()
if err != nil {
panic(err)
}
fmt.Printf("%v\n", inputs)
// Output: [name storage_class]
}
func ExampleModuleDefinition_Outputs() {
module := ModuleDefinition{
Name: "cloud_storage",
Definition: `
resource "google_storage_bucket" "bucket" {
name = "my-bucket"
storage_class = "STANDARD"
}
output id {value = "${google_storage_bucket.bucket.id}"}
output bucket_name {value = "my-bucket"}
`,
}
outputs, err := module.Outputs()
if err != nil {
panic(err)
}
fmt.Printf("%v\n", outputs)
// Output: [bucket_name id]
}
func TestModuleDefinition_Validate(t *testing.T) {
cases := map[string]struct {
Module ModuleDefinition
ErrContains string
}{
"nominal": {
Module: ModuleDefinition{
Name: "my_module",
Definition: `
resource "google_storage_bucket" "bucket" {
name = "my-bucket"
storage_class = "STANDARD"
}`,
},
ErrContains: "",
},
"bad-name": {
Module: ModuleDefinition{
Name: "my module",
Definition: `
resource "google_storage_bucket" "bucket" {
name = "my-bucket"
storage_class = "STANDARD"
}`,
},
ErrContains: "field must match '^[a-z_]*$': Name",
},
"bad-hcl": {
Module: ModuleDefinition{
Name: "my_module",
Definition: `
resource "bucket" {
name = "my-bucket"`,
},
ErrContains: "invalid HCL: Definition",
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
err := tc.Module.Validate()
if tc.ErrContains == "" {
if err != nil {
t.Fatalf("Expected no error but got: %v", err)
}
} else {
if err == nil {
t.Fatalf("Expected error containing %q but got nil", tc.ErrContains)
}
if !strings.Contains(err.Error(), tc.ErrContains) {
t.Fatalf("Expected error containing %q but got %v", tc.ErrContains, 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/providers/tf/wrapper/instance.go | pkg/providers/tf/wrapper/instance.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 wrapper
import "encoding/json"
// ModuleInstance represents the configuration of a single instance of a module.
type ModuleInstance struct {
ModuleName string `json:"module_name"`
InstanceName string `json:"instance_name"`
Configuration map[string]interface{} `json:"configuration"`
}
// MarshalDefinition converts the module instance definition into a JSON
// definition that can be fed to Terraform to be created/destroyed.
func (instance *ModuleInstance) MarshalDefinition() (json.RawMessage, error) {
instanceConfig := make(map[string]interface{})
for k, v := range instance.Configuration {
instanceConfig[k] = v
}
instanceConfig["source"] = instance.ModuleName
defn := map[string]interface{}{
"module": map[string]interface{}{
instance.InstanceName: instanceConfig,
},
}
return json.Marshal(defn)
}
| 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/providers/tf/wrapper/instance_test.go | pkg/providers/tf/wrapper/instance_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 wrapper
import "fmt"
func ExampleModuleInstance_MarshalDefinition() {
instance := ModuleInstance{
ModuleName: "foo-module",
InstanceName: "instance",
Configuration: map[string]interface{}{"foo": "bar"},
}
defnJson, err := instance.MarshalDefinition()
fmt.Println(err)
fmt.Printf("%s\n", string(defnJson))
// Output: <nil>
// {"module":{"instance":{"foo":"bar","source":"foo-module"}}}
}
| 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/providers/tf/wrapper/module.go | pkg/providers/tf/wrapper/module.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 wrapper
import (
"sort"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/hashicorp/hcl"
)
// ModuleDefinition represents a module in a Terraform workspace.
type ModuleDefinition struct {
Name string
Definition string
}
var _ (validation.Validatable) = (*ModuleDefinition)(nil)
// Validate checks the validity of the ModuleDefinition struct.
func (module *ModuleDefinition) Validate() (errs *validation.FieldError) {
return errs.Also(
validation.ErrIfBlank(module.Name, "Name"),
validation.ErrIfNotTerraformIdentifier(module.Name, "Name"),
validation.ErrIfNotHCL(module.Definition, "Definition"),
)
}
// Inputs gets the input parameter names for the module.
func (module *ModuleDefinition) Inputs() ([]string, error) {
defn := terraformModuleHcl{}
if err := hcl.Decode(&defn, module.Definition); err != nil {
return nil, err
}
return sortedKeys(defn.Inputs), nil
}
// Outputs gets the output parameter names for the module.
func (module *ModuleDefinition) Outputs() ([]string, error) {
defn := terraformModuleHcl{}
if err := hcl.Decode(&defn, module.Definition); err != nil {
return nil, err
}
return sortedKeys(defn.Outputs), nil
}
func sortedKeys(m map[string]interface{}) []string {
var keys []string
for key, _ := range m {
keys = append(keys, key)
}
sort.Slice(keys, func(i int, j int) bool { return keys[i] < keys[j] })
return keys
}
// terraformModuleHcl is a struct used for marshaling/unmarshaling details about
// Terraform modules.
//
// See https://www.terraform.io/docs/modules/create.html for their structure.
type terraformModuleHcl struct {
Inputs map[string]interface{} `hcl:"variable"`
Outputs map[string]interface{} `hcl:"output"`
}
| 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/providers/tf/wrapper/workspace_test.go | pkg/providers/tf/wrapper/workspace_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 wrapper
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"reflect"
"testing"
)
func TestTerraformWorkspace_Invariants(t *testing.T) {
// This function tests the following two invariants of the workspace:
// - The function updates the tfstate once finished.
// - The function creates and destroys its own dir.
cases := map[string]struct {
Exec func(ws *TerraformWorkspace)
}{
"validate": {Exec: func(ws *TerraformWorkspace) {
ws.Validate()
}},
"apply": {Exec: func(ws *TerraformWorkspace) {
ws.Apply()
}},
"destroy": {Exec: func(ws *TerraformWorkspace) {
ws.Destroy()
}},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
// construct workspace
ws, err := NewWorkspace(map[string]interface{}{}, ``)
if err != nil {
t.Fatal(err)
}
// substitute the executor so we can validate the state at the time of
// "running" tf
executorRan := false
cmdDir := ""
ws.Executor = func(cmd *exec.Cmd) error {
executorRan = true
cmdDir = cmd.Dir
// validate that the directory exists
_, err := os.Stat(cmd.Dir)
if err != nil {
t.Fatalf("couldn't stat the cmd execution dir %v", err)
}
// write dummy state file
if err := ioutil.WriteFile(path.Join(cmdDir, "terraform.tfstate"), []byte(tn), 0755); err != nil {
t.Fatal(err)
}
return nil
}
// run function
tc.Exec(ws)
// check validator got ran
if !executorRan {
t.Fatal("Executor did not get run as part of the function")
}
// check workspace destroyed
if _, err := os.Stat(cmdDir); !os.IsNotExist(err) {
t.Fatalf("command directory didn't %q get torn down %v", cmdDir, err)
}
// check tfstate updated
if !reflect.DeepEqual(ws.State, []byte(tn)) {
t.Fatalf("Expected state %v got %v", []byte(tn), ws.State)
}
})
}
}
func TestCustomTerraformExecutor(t *testing.T) {
customBinary := "/path/to/terraform"
customPlugins := "/path/to/terraform-plugins"
pluginsFlag := "-plugin-dir=" + customPlugins
cases := map[string]struct {
Input *exec.Cmd
Expected *exec.Cmd
}{
"destroy": {
Input: exec.Command("terraform", "destroy", "-auto-approve", "-no-color"),
Expected: exec.Command(customBinary, "destroy", "-auto-approve", "-no-color"),
},
"apply": {
Input: exec.Command("terraform", "apply", "-auto-approve", "-no-color"),
Expected: exec.Command(customBinary, "apply", "-auto-approve", "-no-color"),
},
"validate": {
Input: exec.Command("terraform", "validate", "-no-color"),
Expected: exec.Command(customBinary, "validate", "-no-color"),
},
"init": {
Input: exec.Command("terraform", "init", "-no-color"),
Expected: exec.Command(customBinary, "init", "-get-plugins=false", pluginsFlag, "-no-color"),
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actual := exec.Command("!actual-never-got-called!")
executor := CustomTerraformExecutor(customBinary, customPlugins, func(c *exec.Cmd) error {
actual = c
return nil
})
executor(tc.Input)
if actual.Path != tc.Expected.Path {
t.Errorf("path wasn't updated, expected: %q, actual: %q", tc.Expected.Path, actual.Path)
}
if !reflect.DeepEqual(actual.Args, tc.Expected.Args) {
t.Errorf("args weren't updated correctly, expected: %#v, actual: %#v", tc.Expected.Args, actual.Args)
}
})
}
}
func TestCustomEnvironmentExecutor(t *testing.T) {
c := exec.Command("/path/to/terraform", "apply")
c.Env = []string{"ORIGINAL=value"}
actual := exec.Command("!actual-never-got-called!")
executor := CustomEnvironmentExecutor(map[string]string{"FOO": "bar"}, func(c *exec.Cmd) error {
actual = c
return nil
})
executor(c)
expected := []string{"ORIGINAL=value", "FOO=bar"}
if !reflect.DeepEqual(expected, actual.Env) {
fmt.Errorf("Expected %v actual %v", 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/providers/tf/wrapper/workspace.go | pkg/providers/tf/wrapper/workspace.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 wrapper
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"sync"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
)
// DefaultInstanceName is the default name of an instance of a particular module.
const (
DefaultInstanceName = "instance"
)
var (
FsInitializationErr = errors.New("Filesystem must first be initialized.")
)
// TerraformExecutor is the function that shells out to Terraform.
// It can intercept, modify or retry the given command.
type TerraformExecutor func(*exec.Cmd) error
// NewWorkspace creates a new TerraformWorkspace from a given template and variables to populate an instance of it.
// The created instance will have the name specified by the DefaultInstanceName constant.
func NewWorkspace(templateVars map[string]interface{}, terraformTemplate string) (*TerraformWorkspace, error) {
tfModule := ModuleDefinition{
Name: "brokertemplate",
Definition: terraformTemplate,
}
inputList, err := tfModule.Inputs()
if err != nil {
return nil, err
}
limitedConfig := make(map[string]interface{})
for _, name := range inputList {
limitedConfig[name] = templateVars[name]
}
workspace := TerraformWorkspace{
Modules: []ModuleDefinition{tfModule},
Instances: []ModuleInstance{
{
ModuleName: tfModule.Name,
InstanceName: DefaultInstanceName,
Configuration: limitedConfig,
},
},
}
return &workspace, nil
}
// DeserializeWorkspace creates a new TerraformWorkspace from a given JSON
// serialization of one.
func DeserializeWorkspace(definition string) (*TerraformWorkspace, error) {
ws := TerraformWorkspace{}
if err := json.Unmarshal([]byte(definition), &ws); err != nil {
return nil, err
}
return &ws, nil
}
// TerraformWorkspace represents the directory layout of a Terraform execution.
// The structure is strict, consiting of several Terraform modules and instances
// of those modules. The strictness is artificial, but maintains a clear
// separation between data and code.
//
// It manages the directory structure needed for the commands, serializing and
// deserializing Terraform state, and all the flags necessary to call Terraform.
//
// All public functions that shell out to Terraform maintain the following invariants:
// - The function blocks if another terraform shell is running.
// - The function updates the tfstate once finished.
// - The function creates and destroys its own dir.
type TerraformWorkspace struct {
Modules []ModuleDefinition `json:"modules"`
Instances []ModuleInstance `json:"instances"`
State []byte `json:"tfstate"`
// Executor is a function that gets invoked to shell out to Terraform.
// If left nil, the default executor is used.
Executor TerraformExecutor `json:"-"`
dirLock sync.Mutex
dir string
}
// String returns a human-friendly representation of the workspace suitable for
// printing to the console.
func (workspace *TerraformWorkspace) String() string {
var b strings.Builder
b.WriteString("# Terraform Workspace\n")
fmt.Fprintf(&b, "modules: %d\n", len(workspace.Modules))
fmt.Fprintf(&b, "instances: %d\n", len(workspace.Instances))
fmt.Fprintln(&b)
for _, instance := range workspace.Instances {
fmt.Fprintf(&b, "## Instance %q\n", instance.InstanceName)
fmt.Fprintf(&b, "module = %q\n", instance.ModuleName)
for k, v := range instance.Configuration {
fmt.Fprintf(&b, "input.%s = %#v\n", k, v)
}
if outputs, err := workspace.Outputs(instance.InstanceName); err != nil {
for k, v := range outputs {
fmt.Fprintf(&b, "output.%s = %#v\n", k, v)
}
}
fmt.Fprintln(&b)
}
return b.String()
}
// Serialize converts the TerraformWorkspace into a JSON string.
func (workspace *TerraformWorkspace) Serialize() (string, error) {
ws, err := json.Marshal(workspace)
if err != nil {
return "", err
}
return string(ws), nil
}
// initializeFs initializes the filesystem directory necessary to run Terraform.
func (workspace *TerraformWorkspace) initializeFs() error {
workspace.dirLock.Lock()
// create a temp directory
if dir, err := ioutil.TempDir("", "gsb"); err != nil {
return err
} else {
workspace.dir = dir
}
// write the modulesTerraformWorkspace
for _, module := range workspace.Modules {
parent := path.Join(workspace.dir, module.Name)
if err := os.Mkdir(parent, 0755); err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(parent, "definition.tf"), []byte(module.Definition), 0755); err != nil {
return err
}
}
// write the instances
for _, instance := range workspace.Instances {
contents, err := instance.MarshalDefinition()
if err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(workspace.dir, instance.InstanceName+".tf"), contents, 0755); err != nil {
return err
}
}
// write the state if it exists
if len(workspace.State) > 0 {
if err := ioutil.WriteFile(workspace.tfStatePath(), workspace.State, 0755); err != nil {
return err
}
}
// run "terraform init"
if err := workspace.runTf("init", "-no-color"); err != nil {
return err
}
return nil
}
// TeardownFs removes the directory we executed Terraform in and updates the
// state from it.
func (workspace *TerraformWorkspace) teardownFs() error {
bytes, err := ioutil.ReadFile(workspace.tfStatePath())
if err != nil {
return err
}
workspace.State = bytes
if err := os.RemoveAll(workspace.dir); err != nil {
return err
}
workspace.dir = ""
workspace.dirLock.Unlock()
return nil
}
// Outputs gets the Terraform outputs from the state for the instance with the
// given name. This function DOES NOT invoke Terraform and instead uses the stored state.
// If no instance exists with the given name, it could be that Terraform pruned it due
// to having no contents so a blank map is returned.
func (workspace *TerraformWorkspace) Outputs(instance string) (map[string]interface{}, error) {
state, err := NewTfstate(workspace.State)
if err != nil {
return nil, err
}
// All root project modules get put under the "root" namespace
module := state.GetModule("root", instance)
// Terraform prunes modules with no contents, so we return blank results.
if module == nil {
return map[string]interface{}{}, nil
}
return module.GetOutputs(), nil
}
// Validate runs `terraform Validate` on this workspace.
// This funciton blocks if another Terraform command is running on this workspace.
func (workspace *TerraformWorkspace) Validate() error {
err := workspace.initializeFs()
defer workspace.teardownFs()
if err != nil {
return err
}
return workspace.runTf("validate", "-no-color")
}
// Apply runs `terraform apply` on this workspace.
// This funciton blocks if another Terraform command is running on this workspace.
func (workspace *TerraformWorkspace) Apply() error {
err := workspace.initializeFs()
defer workspace.teardownFs()
if err != nil {
return err
}
return workspace.runTf("apply", "-auto-approve", "-no-color")
}
// Destroy runs `terraform destroy` on this workspace.
// This funciton blocks if another Terraform command is running on this workspace.
func (workspace *TerraformWorkspace) Destroy() error {
err := workspace.initializeFs()
defer workspace.teardownFs()
if err != nil {
return err
}
return workspace.runTf("destroy", "-auto-approve", "-no-color")
}
func (workspace *TerraformWorkspace) tfStatePath() string {
return path.Join(workspace.dir, "terraform.tfstate")
}
func (workspace *TerraformWorkspace) runTf(subCommand string, args ...string) error {
sub := []string{subCommand}
sub = append(sub, args...)
c := exec.Command("terraform", sub...)
c.Env = os.Environ()
c.Dir = workspace.dir
executor := DefaultExecutor
if workspace.Executor != nil {
executor = workspace.Executor
}
return executor(c)
}
// CustomEnvironmentExecutor sets custom environment variables on the Terraform
// execution.
func CustomEnvironmentExecutor(environment map[string]string, wrapped TerraformExecutor) TerraformExecutor {
return func(c *exec.Cmd) error {
for k, v := range environment {
c.Env = append(c.Env, fmt.Sprintf("%s=%s", k, v))
}
return wrapped(c)
}
}
// CustomTerraformExecutor executes a custom Terraform binary that uses plugins
// from a given plugin directory rather than the Terraform that's on the PATH
// which will download provider binaries from the web.
func CustomTerraformExecutor(tfBinaryPath, tfPluginDir string, wrapped TerraformExecutor) TerraformExecutor {
return func(c *exec.Cmd) error {
// Add the -get-plugins=false and -plugin-dir={tfPluginDir} after the
// sub-command to force Terraform to use a particular plugin.
subCommand := c.Args[1]
subCommandArgs := c.Args[2:]
if subCommand == "init" {
subCommandArgs = append([]string{"-get-plugins=false", fmt.Sprintf("-plugin-dir=%s", tfPluginDir)}, subCommandArgs...)
}
allArgs := append([]string{subCommand}, subCommandArgs...)
newCmd := exec.Command(tfBinaryPath, allArgs...)
newCmd.Dir = c.Dir
newCmd.Env = c.Env
return wrapped(newCmd)
}
}
// DefaultExecutor is the default executor that shells out to Terraform
// and logs results to stdout.
func DefaultExecutor(c *exec.Cmd) error {
logger := utils.NewLogger("terraform@" + c.Dir)
logger.Info("starting process", lager.Data{
"path": c.Path,
"args": c.Args,
"dir": c.Dir,
})
output, err := c.CombinedOutput()
logger.Info("results", lager.Data{
"output": string(output),
"error": err,
})
return 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/providers/builtin/registry.go | pkg/providers/builtin/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 builtin
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/bigquery"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/bigtable"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/cloudsql"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/dataflow"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/datastore"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/dialogflow"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/filestore"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/firestore"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/ml"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/pubsub"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/redis"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/spanner"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/stackdriver"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/storage"
)
// NOTE(josephlewis42) unless there are extenuating circumstances, as of 2019
// no new builtin providers should be added. Instead, providers should be
// added using downloadable brokerpaks.
// BuiltinBrokerRegistry creates a new registry with all the built-in brokers
// added to it.
func BuiltinBrokerRegistry() broker.BrokerRegistry {
out := broker.BrokerRegistry{}
RegisterBuiltinBrokers(out)
return out
}
// RegisterBuiltinBrokers adds the built-in brokers to the given registry.
func RegisterBuiltinBrokers(registry broker.BrokerRegistry) {
registry.Register(ml.ServiceDefinition())
registry.Register(bigquery.ServiceDefinition())
registry.Register(bigtable.ServiceDefinition())
registry.Register(cloudsql.MysqlServiceDefinition())
registry.Register(cloudsql.PostgresServiceDefinition())
registry.Register(cloudsql.MySQLVPCServiceDefinition())
registry.Register(cloudsql.PostgresVPCServiceDefinition())
registry.Register(dataflow.ServiceDefinition())
registry.Register(datastore.ServiceDefinition())
registry.Register(dialogflow.ServiceDefinition())
registry.Register(firestore.ServiceDefinition())
registry.Register(pubsub.ServiceDefinition())
registry.Register(redis.ServiceDefinition())
registry.Register(spanner.ServiceDefinition())
registry.Register(stackdriver.StackdriverDebuggerServiceDefinition())
registry.Register(stackdriver.StackdriverMonitoringServiceDefinition())
registry.Register(stackdriver.StackdriverProfilerServiceDefinition())
registry.Register(stackdriver.StackdriverTraceServiceDefinition())
registry.Register(storage.ServiceDefinition())
registry.Register(filestore.ServiceDefinition())
}
| 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/providers/builtin/builtins_test.go | pkg/providers/builtin/builtins_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 builtin
import (
"context"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base/basefakes"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/bigquery"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/bigtable"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/cloudsql"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/dataflow"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/datastore"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/dialogflow"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/firestore"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/ml"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/pubsub"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/spanner"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/stackdriver"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/storage"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
)
func TestServiceProviderAsync(t *testing.T) {
cases := map[string]struct {
AsyncProvisionExpected bool
AsyncDeprovisionExpected bool
Provider broker.ServiceProvider
}{
"ml": {
Provider: &ml.ApiServiceBroker{},
},
"bigquery": {
Provider: &bigquery.BigQueryBroker{},
},
"bigtable": {
Provider: &bigtable.BigTableBroker{},
},
"cloudsql": {
AsyncProvisionExpected: true,
AsyncDeprovisionExpected: false,
Provider: &cloudsql.CloudSQLBroker{},
},
"dataflow": {
Provider: &dataflow.DataflowBroker{},
},
"datastore": {
Provider: &datastore.DatastoreBroker{},
},
"dialogflow": {
Provider: &dialogflow.DialogflowBroker{},
},
"firestore": {
Provider: &firestore.FirestoreBroker{},
},
"pubsub": {
Provider: &pubsub.PubSubBroker{},
},
"spanner": {
AsyncProvisionExpected: true,
Provider: &spanner.SpannerBroker{},
},
"storage": {
Provider: &storage.StorageBroker{},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
actualProvisionAsync := tc.Provider.ProvisionsAsync()
if tc.AsyncProvisionExpected != actualProvisionAsync {
t.Errorf("Expected async provision to match. Expected: %t, Actual: %t", tc.AsyncProvisionExpected, actualProvisionAsync)
}
actualDeprovisionAsync := tc.Provider.DeprovisionsAsync()
if tc.AsyncDeprovisionExpected != actualDeprovisionAsync {
t.Errorf("Expected async deprovision to match. Expected: %t, Actual: %t", tc.AsyncDeprovisionExpected, actualDeprovisionAsync)
}
})
}
}
func TestThinWrapperServiceProviders(t *testing.T) {
cases := map[string]func(base.BrokerBase) broker.ServiceProvider{
"pubsub": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &pubsub.PubSubBroker{BrokerBase: brokerBase}
},
"stackdriver": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &stackdriver.StackdriverAccountProvider{BrokerBase: brokerBase}
},
"ml": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &ml.ApiServiceBroker{BrokerBase: brokerBase}
},
"bigquery": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &bigquery.BigQueryBroker{BrokerBase: brokerBase}
},
"dataflow": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &dataflow.DataflowBroker{BrokerBase: brokerBase}
},
"datastore": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &datastore.DatastoreBroker{BrokerBase: brokerBase}
},
"dialogflow": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &dialogflow.DialogflowBroker{BrokerBase: brokerBase}
},
"firestore": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &firestore.FirestoreBroker{BrokerBase: brokerBase}
},
"spanner": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &spanner.SpannerBroker{BrokerBase: brokerBase}
},
"storage": func(brokerBase base.BrokerBase) broker.ServiceProvider {
return &storage.StorageBroker{BrokerBase: brokerBase}
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
accountManager := basefakes.FakeServiceAccountManager{}
brokerBase := base.BrokerBase{
AccountManager: &accountManager,
}
serviceProvider := tc(brokerBase)
if _, err := serviceProvider.Bind(context.Background(), &varcontext.VarContext{}); err != nil {
t.Fatal(err)
}
if accountManager.CreateCredentialsCallCount() != 1 {
t.Errorf("Expected CreateCredentials to be called once. Expected: %d, Actual: %d", 1, accountManager.CreateCredentialsCallCount())
}
if err := serviceProvider.Unbind(context.Background(), models.ServiceInstanceDetails{}, models.ServiceBindingCredentials{}); err != nil {
t.Fatal(err)
}
if accountManager.DeleteCredentialsCallCount() != 1 {
t.Errorf("Expected DeleteCredentials to be called once. Expected: %d, Actual: %d", 1, accountManager.DeleteCredentialsCallCount())
}
})
}
}
| 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/providers/builtin/registry_test.go | pkg/providers/builtin/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 builtin
import (
"reflect"
"sort"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
)
func TestBuiltinBrokerRegistry(t *testing.T) {
builtinServiceNames := []string{
"google-bigquery",
"google-bigtable",
"google-cloudsql-mysql",
"google-cloudsql-mysql-vpc",
"google-cloudsql-postgres",
"google-cloudsql-postgres-vpc",
"google-dataflow",
"google-datastore",
"google-dialogflow",
"google-filestore",
"google-firestore",
"google-memorystore-redis",
"google-ml-apis",
"google-pubsub",
"google-spanner",
"google-stackdriver-debugger",
"google-stackdriver-monitoring",
"google-stackdriver-profiler",
"google-stackdriver-trace",
"google-storage",
}
sort.Strings(builtinServiceNames)
t.Run("service-count", func(t *testing.T) {
expectedServiceCount := len(builtinServiceNames)
actualServiceCount := len(BuiltinBrokerRegistry())
if actualServiceCount != expectedServiceCount {
t.Errorf("Expected %d services, registered: %d", expectedServiceCount, actualServiceCount)
}
})
t.Run("service-names", func(t *testing.T) {
var actual []string
registry := BuiltinBrokerRegistry()
for name, _ := range registry {
actual = append(actual, name)
}
sort.Strings(actual)
if !reflect.DeepEqual(builtinServiceNames, actual) {
t.Errorf("Expected service names: %v, got: %v", builtinServiceNames, actual)
}
})
for _, svc := range BuiltinBrokerRegistry() {
validateServiceDefinition(t, svc)
}
}
func validateServiceDefinition(t *testing.T, svc *broker.ServiceDefinition) {
t.Run("service:"+svc.Name, func(t *testing.T) {
if !svc.IsBuiltin {
t.Errorf("Expected flag 'builtin' to be set, but it was: %t", svc.IsBuiltin)
}
catalog, err := svc.CatalogEntry()
if err != nil {
t.Fatal(err)
}
if catalog.PlanUpdatable {
t.Error("Expected PlanUpdatable to be false")
}
if catalog.InstancesRetrievable {
t.Error("Expected InstancesRetrievable to be false")
}
if catalog.BindingsRetrievable {
t.Error("Expected BindingsRetrievable to be false")
}
for _, v := range svc.Examples {
t.Run("example:"+v.Name, func(t *testing.T) {
if err := broker.ValidateVariables(v.ProvisionParams, svc.ProvisionInputVariables); err != nil {
t.Errorf("expected valid provision vars: %v", err)
}
if err := broker.ValidateVariables(v.BindParams, svc.BindInputVariables); err != nil {
t.Errorf("expected valid bind vars: %v", err)
}
})
}
// All fields should be optional for UX purposes when using with Cloud Foundry
for _, v := range svc.ProvisionInputVariables {
if v.Required {
t.Errorf("No provision fields should be marked as required but %q was", v.FieldName)
}
}
for _, v := range svc.BindInputVariables {
if v.Required {
t.Errorf("No bind fields should be marked as required but %q was", v.FieldName)
}
}
if len(svc.Description) > 255 {
t.Errorf("CF requires description lengths to be less than 255 characters, but got %d", len(svc.Description))
}
for _, plan := range catalog.Plans {
validateServicePlan(t, svc, plan)
}
})
}
func validateServicePlan(t *testing.T, svc *broker.ServiceDefinition, plan broker.ServicePlan) {
t.Run("plan:"+plan.Name, func(t *testing.T) {
if plan.Free == nil {
t.Error("Expected plan to have free/cost setting but was 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/providers/builtin/bigquery/broker.go | pkg/providers/builtin/bigquery/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 bigquery
import (
"context"
"fmt"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
googlebigquery "google.golang.org/api/bigquery/v2"
)
// BigQueryBroker is the service-broker back-end for creating and binding BigQuery instances.
type BigQueryBroker struct {
base.BrokerBase
}
// InstanceInformation holds the details needed to bind a service account to a BigQuery instance after it has been provisioned.
type InstanceInformation struct {
DatasetId string `json:"dataset_id"`
}
// Provision creates a new BigQuery dataset from the settings in the user-provided details and service plan.
func (b *BigQueryBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
service, err := b.createClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
d := googlebigquery.Dataset{
Location: provisionContext.GetString("location"),
DatasetReference: &googlebigquery.DatasetReference{
DatasetId: provisionContext.GetString("name"),
},
Labels: provisionContext.GetStringMapString("labels"),
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
newDataset, err := service.Datasets.Insert(b.ProjectId, &d).Do()
if err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error inserting new dataset: %s", err)
}
ii := InstanceInformation{
DatasetId: newDataset.DatasetReference.DatasetId,
}
id := models.ServiceInstanceDetails{
Name: newDataset.DatasetReference.DatasetId,
Url: newDataset.SelfLink,
Location: newDataset.Location,
}
if err := id.SetOtherDetails(ii); err != nil {
return models.ServiceInstanceDetails{}, err
}
return id, nil
}
// Deprovision deletes the dataset associated with the given instance.
// Note: before deprovisioning you must delete all the tables in the dataset.
func (b *BigQueryBroker) Deprovision(ctx context.Context, dataset models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
service, err := b.createClient(ctx)
if err != nil {
return nil, err
}
if err := service.Datasets.Delete(b.ProjectId, dataset.Name).Do(); err != nil {
return nil, fmt.Errorf("Error deleting dataset: %s", err)
}
return nil, nil
}
func (b *BigQueryBroker) createClient(ctx context.Context) (*googlebigquery.Service, error) {
service, err := googlebigquery.New(b.HttpConfig.Client(ctx))
if err != nil {
return nil, fmt.Errorf("Couldn't instantiate BigQuery API client: %s", err)
}
service.UserAgent = utils.CustomUserAgent
return service, 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/providers/builtin/bigquery/definition.go | pkg/providers/builtin/bigquery/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 bigquery
import (
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the BigQuery service.
func ServiceDefinition() *broker.ServiceDefinition {
roleWhitelist := []string{
"bigquery.dataViewer",
"bigquery.dataEditor",
"bigquery.dataOwner",
"bigquery.user",
"bigquery.jobUser",
}
return &broker.ServiceDefinition{
Id: "f80c0a3e-bd4d-4809-a900-b4e33a6450f1",
Name: "google-bigquery",
Description: "A fast, economical and fully managed data warehouse for large-scale data analytics.",
DisplayName: "Google BigQuery",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/bigquery.svg",
DocumentationUrl: "https://cloud.google.com/bigquery/docs/",
SupportUrl: "https://cloud.google.com/bigquery/support",
Tags: []string{"gcp", "bigquery"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "10ff4e72-6e84-44eb-851f-bdb38a791914",
Name: "default",
Description: "BigQuery default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
{
FieldName: "name",
Type: broker.JsonTypeString,
Details: "The name of the BigQuery dataset.",
Default: "pcf_sb_${counter.next()}_${time.nano()}",
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z0-9_]+$").
MaxLength(1024).
Build(),
},
{
FieldName: "location",
Type: broker.JsonTypeString,
Details: "The location of the BigQuery instance.",
Default: "US",
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Examples("US", "EU", "asia-northeast1").
Build(),
},
},
ProvisionComputedVariables: []varcontext.DefaultVariable{
{Name: "labels", Default: "${json.marshal(request.default_labels)}", Overwrite: true},
},
DefaultRoleWhitelist: roleWhitelist,
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist, "bigquery.user"),
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
BindOutputVariables: append(accountmanagers.ServiceAccountBindOutputVariables(),
broker.BrokerVariable{
FieldName: "dataset_id",
Type: broker.JsonTypeString,
Details: "The name of the BigQuery dataset.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z0-9_]+$").
MaxLength(1024).
Build(),
},
),
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Create a dataset and account that can manage and query the data.",
PlanId: "10ff4e72-6e84-44eb-851f-bdb38a791914",
ProvisionParams: map[string]interface{}{
"name": "orders_1997",
},
BindParams: map[string]interface{}{
"role": "bigquery.user",
},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &BigQueryBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/pubsub/broker.go | pkg/providers/builtin/pubsub/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 pubsub
import (
"errors"
googlepubsub "cloud.google.com/go/pubsub"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/net/context"
"fmt"
"time"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"google.golang.org/api/option"
)
// PubSubBroker is the service-broker back-end for creating Google Pub/Sub
// topics, subscriptions, and accounts.
type PubSubBroker struct {
base.BrokerBase
}
// InstanceInformation holds the details needed to connect to a PubSub instance
// after it has been provisioned.
type InstanceInformation struct {
TopicName string `json:"topic_name"`
// SubscriptionName is optional, if non-empty then a susbcription was created.
SubscriptionName string `json:"subscription_name"`
}
// Provision creates a new Pub/Sub topic from the settings in the user-provided details and service plan.
// If a subscription name is supplied, the function will also create a subscription for the topic.
func (b *PubSubBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
// Extract and validate all the params exist and are the right types
defaultLabels := provisionContext.GetStringMapString("labels")
topicName := provisionContext.GetString("topic_name")
subscriptionName := provisionContext.GetString("subscription_name")
endpoint := ""
if provisionContext.GetBool("is_push") {
endpoint = provisionContext.GetString("endpoint")
}
subscriptionConfig := googlepubsub.SubscriptionConfig{
PushConfig: googlepubsub.PushConfig{
Endpoint: endpoint,
},
AckDeadline: time.Duration(provisionContext.GetInt("ack_deadline")) * time.Second,
Labels: defaultLabels,
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
// Check special-cases
if topicName == "" {
return models.ServiceInstanceDetails{}, errors.New("topic_name must not be blank")
}
// Create
pubsubClient, err := b.createClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
topic, err := pubsubClient.CreateTopic(ctx, topicName)
if err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error creating new Pub/Sub topic: %s", err)
}
// This service needs labels to be set after creation
if _, err := topic.Update(ctx, googlepubsub.TopicConfigToUpdate{Labels: defaultLabels}); err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error setting labels on new Pub/Sub topic: %s", err)
}
if subscriptionName != "" {
subscriptionConfig.Topic = topic
if _, err := pubsubClient.CreateSubscription(ctx, subscriptionName, subscriptionConfig); err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error creating subscription: %s", err)
}
}
ii := InstanceInformation{
TopicName: topicName,
SubscriptionName: subscriptionName,
}
id := models.ServiceInstanceDetails{
Name: topicName,
Url: "",
Location: "",
}
if err := id.SetOtherDetails(ii); err != nil {
return models.ServiceInstanceDetails{}, err
}
return id, err
}
// Deprovision deletes the topic and subscription associated with the given instance.
func (b *PubSubBroker) Deprovision(ctx context.Context, topic models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
service, err := b.createClient(ctx)
if err != nil {
return nil, err
}
if err := service.Topic(topic.Name).Delete(ctx); err != nil {
return nil, fmt.Errorf("Error deleting pubsub topic: %s", err)
}
otherDetails := InstanceInformation{}
if err := topic.GetOtherDetails(&otherDetails); err != nil {
return nil, err
}
if otherDetails.SubscriptionName != "" {
if err := service.Subscription(otherDetails.SubscriptionName).Delete(ctx); err != nil {
return nil, fmt.Errorf("Error deleting subscription: %s", err)
}
}
return nil, nil
}
func (b *PubSubBroker) createClient(ctx context.Context) (*googlepubsub.Client, error) {
co := option.WithUserAgent(utils.CustomUserAgent)
ct := option.WithTokenSource(b.HttpConfig.TokenSource(ctx))
client, err := googlepubsub.NewClient(ctx, b.ProjectId, co, ct)
if err != nil {
return nil, fmt.Errorf("Couldn't instantiate Pub/Sub API client: %s", 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/providers/builtin/pubsub/definition.go | pkg/providers/builtin/pubsub/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 pubsub
import (
"code.cloudfoundry.org/lager"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Pub/Sub service.
func ServiceDefinition() *broker.ServiceDefinition {
roleWhitelist := []string{
"pubsub.publisher",
"pubsub.subscriber",
"pubsub.viewer",
"pubsub.editor",
}
return &broker.ServiceDefinition{
Id: "628629e3-79f5-4255-b981-d14c6c7856be",
Name: "google-pubsub",
Description: "A global service for real-time and reliable messaging and streaming data.",
DisplayName: "Google PubSub",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/pubsub.svg",
DocumentationUrl: "https://cloud.google.com/pubsub/docs/",
SupportUrl: "https://cloud.google.com/pubsub/docs/support",
Tags: []string{"gcp", "pubsub"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "622f4da3-8731-492a-af29-66a9146f8333",
Name: "default",
Description: "PubSub Default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
{
FieldName: "topic_name",
Type: broker.JsonTypeString,
Details: `Name of the topic. Must not start with "goog".`,
Default: "pcf_sb_${counter.next()}_${time.nano()}",
Constraints: validation.NewConstraintBuilder().
MinLength(3).
MaxLength(255).
Pattern(`^[a-zA-Z][a-zA-Z0-9\d\-_~%\.\+]+$`). // adapted from the Pub/Sub create topic page's validator
Build(),
},
{
FieldName: "subscription_name",
Type: broker.JsonTypeString,
Details: `Name of the subscription. Blank means no subscription will be created. Must not start with "goog".`,
Default: "",
Constraints: validation.NewConstraintBuilder().
MinLength(0).
MaxLength(255).
Pattern(`^(|[a-zA-Z][a-zA-Z0-9\d\-_~%\.\+]+)`). // adapted from the Pub/Sub create subscription page's validator
Build(),
},
{
FieldName: "is_push",
Type: broker.JsonTypeString,
Details: `Are events handled by POSTing to a URL?`,
Default: "false",
Enum: map[interface{}]string{
"true": "The subscription will POST the events to a URL.",
"false": "Events will be pulled from the subscription.",
},
},
{
FieldName: "endpoint",
Type: broker.JsonTypeString,
Details: "If `is_push` == 'true', then this is the URL that will be pushed to.",
Default: "",
},
{
FieldName: "ack_deadline",
Type: broker.JsonTypeString,
Details: `Value is in seconds. Max: 600
This is the maximum time after a subscriber receives a message
before the subscriber should acknowledge the message. After message
delivery but before the ack deadline expires and before the message is
acknowledged, it is an outstanding message and will not be delivered
again during that time (on a best-effort basis).
`,
Default: "10",
},
},
ProvisionComputedVariables: []varcontext.DefaultVariable{
{Name: "labels", Default: "${json.marshal(request.default_labels)}", Overwrite: true},
},
DefaultRoleWhitelist: roleWhitelist,
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist, "pubsub.editor"),
BindOutputVariables: append(accountmanagers.ServiceAccountBindOutputVariables(),
broker.BrokerVariable{
FieldName: "subscription_name",
Type: broker.JsonTypeString,
Details: "Name of the subscription.",
Required: false,
Constraints: validation.NewConstraintBuilder().
MinLength(0). // subscription name could be blank on return
MaxLength(255).
Pattern(`^(|[a-zA-Z][a-zA-Z0-9\d\-_~%\.\+]+)`). // adapted from the Pub/Sub create subscription page's validator
Build(),
},
broker.BrokerVariable{
FieldName: "topic_name",
Type: broker.JsonTypeString,
Details: "Name of the topic.",
Required: true,
Constraints: validation.NewConstraintBuilder().
MinLength(3).
MaxLength(255).
Pattern(`^[a-zA-Z][a-zA-Z0-9\d\-_~%\.\+]+$`). // adapted from the Pub/Sub create topic page's validator
Build(),
},
),
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Create a topic and a publisher to it.",
PlanId: "622f4da3-8731-492a-af29-66a9146f8333",
ProvisionParams: map[string]interface{}{
"topic_name": "example_topic",
"subscription_name": "example_topic_subscription",
},
BindParams: map[string]interface{}{
"role": "pubsub.publisher",
},
},
{
Name: "No Subscription",
Description: "Create a topic without a subscription.",
PlanId: "622f4da3-8731-492a-af29-66a9146f8333",
ProvisionParams: map[string]interface{}{
"topic_name": "example_topic",
},
BindParams: map[string]interface{}{
"role": "pubsub.publisher",
},
},
{
Name: "Custom Timeout",
Description: "Create a subscription with a custom deadline for long processess.",
PlanId: "622f4da3-8731-492a-af29-66a9146f8333",
ProvisionParams: map[string]interface{}{
"topic_name": "long_deadline_topic",
"subscription_name": "long_deadline_subscription",
"ack_deadline": "200",
},
BindParams: map[string]interface{}{
"role": "pubsub.publisher",
},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &PubSubBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/ml/broker.go | pkg/providers/builtin/ml/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 ml
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
// ApiServiceBroker is the service-broker back-end for creating Google Machine Learning API accounts.
type ApiServiceBroker struct {
base.BrokerBase
}
// Provision is a no-op call because only service accounts need to be bound/unbound for Google Machine Learning APIs.
func (b *ApiServiceBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
return models.ServiceInstanceDetails{}, nil
}
// Deprovision is a no-op call because only service accounts need to be bound/unbound for Google Machine Learning APIs.
func (b *ApiServiceBroker) Deprovision(ctx context.Context, dataset models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
return nil, 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/providers/builtin/ml/definition.go | pkg/providers/builtin/ml/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 ml
import (
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the ML service.
func ServiceDefinition() *broker.ServiceDefinition {
roleWhitelist := []string{
"ml.developer",
"ml.viewer",
"ml.modelOwner",
"ml.modelUser",
"ml.jobOwner",
"ml.operationOwner",
}
return &broker.ServiceDefinition{
Id: "5ad2dce0-51f7-4ede-8b46-293d6df1e8d4",
Name: "google-ml-apis",
Description: "Machine Learning APIs including Vision, Translate, Speech, and Natural Language.",
DisplayName: "Google Machine Learning APIs",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/machine-learning.svg",
DocumentationUrl: "https://cloud.google.com/ml/",
SupportUrl: "https://cloud.google.com/support/",
Tags: []string{"gcp", "ml"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "be7954e1-ecfb-4936-a0b6-db35e6424c7a",
Name: "default",
Description: "Machine Learning API default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
DefaultRoleWhitelist: roleWhitelist,
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist, "ml.modelUser"),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Create an account with developer access to your ML models.",
PlanId: "be7954e1-ecfb-4936-a0b6-db35e6424c7a",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{
"role": "ml.developer",
},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &ApiServiceBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/storage/broker.go | pkg/providers/builtin/storage/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 storage
import (
"fmt"
googlestorage "cloud.google.com/go/storage"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/net/context"
"google.golang.org/api/option"
)
// StorageBroker is the service-broker back-end for creating and binding to
// Google Cloud Storage buckets.
type StorageBroker struct {
base.BrokerBase
}
// InstanceInformation holds the details needed to connect to a GCS instance
// after it has been provisioned.
type InstanceInformation struct {
BucketName string `json:"bucket_name"`
}
// Provision creates a new GCS bucket from the settings in the user-provided details and service plan.
func (b *StorageBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
attrs := googlestorage.BucketAttrs{
Name: provisionContext.GetString("name"),
StorageClass: provisionContext.GetString("storage_class"),
Location: provisionContext.GetString("location"),
Labels: provisionContext.GetStringMapString("labels"),
}
if provisionContext.GetBool("force_delete") {
attrs.Labels["sb-force-delete"] = "true"
} else {
attrs.Labels["sb-force-delete"] = "false"
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
// make a new bucket
storageService, err := b.createClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
// create the bucket. Nil uses default bucket attributes
if err := storageService.Bucket(attrs.Name).Create(ctx, b.ProjectId, &attrs); err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error creating new bucket: %s", err)
}
ii := InstanceInformation{
BucketName: attrs.Name,
}
id := models.ServiceInstanceDetails{
Name: attrs.Name,
Location: attrs.Location,
}
if err := id.SetOtherDetails(ii); err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error marshalling json: %s", err)
}
return id, nil
}
// Deprovision deletes the bucket associated with the given instance.
// Note that all objects within the bucket must be deleted first.
func (b *StorageBroker) Deprovision(ctx context.Context, bucket models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
storageService, err := b.createClient(ctx)
if err != nil {
return nil, err
}
attrs, err := storageService.Bucket(bucket.Name).Attrs(ctx)
if err != nil {
return nil, err
}
if attrs.Labels["sb-force-delete"] == "true" {
objects := storageService.Bucket(bucket.Name).Objects(ctx, nil)
for {
obj, err := objects.Next()
if err != nil || obj == nil {
break
}
storageService.Bucket(bucket.Name).Object(obj.Name).Delete(ctx)
}
}
if err = storageService.Bucket(bucket.Name).Delete(ctx); err != nil {
return nil, fmt.Errorf("error deleting bucket: %s (to delete a non-empty bucket, set the label sb-force-delete=true on it)", err)
}
return nil, nil
}
func (b *StorageBroker) createClient(ctx context.Context) (*googlestorage.Client, error) {
co := option.WithUserAgent(utils.CustomUserAgent)
ct := option.WithTokenSource(b.HttpConfig.TokenSource(ctx))
storageService, err := googlestorage.NewClient(ctx, co, ct)
if err != nil {
return nil, fmt.Errorf("Couldn't instantiate Cloud Storage API client: %s", err)
}
return storageService, 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/providers/builtin/storage/definition.go | pkg/providers/builtin/storage/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 storage
import (
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
const StorageName = "google-storage"
// ServiceDefinition creates a new ServiceDefinition object for the Cloud Storage service.
func ServiceDefinition() *broker.ServiceDefinition {
roleWhitelist := []string{
"storage.objectCreator",
"storage.objectViewer",
"storage.objectAdmin",
}
return &broker.ServiceDefinition{
Id: "b9e4332e-b42b-4680-bda5-ea1506797474",
Name: StorageName,
Description: "Unified object storage for developers and enterprises. Cloud Storage allows world-wide storage and retrieval of any amount of data at any time.",
DisplayName: "Google Cloud Storage",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/storage.svg",
DocumentationUrl: "https://cloud.google.com/storage/docs/overview",
SupportUrl: "https://cloud.google.com/storage/docs/getting-support",
Tags: []string{"gcp", "storage"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "e1d11f65-da66-46ad-977c-6d56513baf43",
Name: "standard",
Description: "Standard storage class. Auto-selects either regional or multi-regional based on the location.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_class": "STANDARD"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "a42c1182-d1a0-4d40-82c1-28220518b360",
Name: "nearline",
Description: "Nearline storage class.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_class": "NEARLINE"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "1a1f4fe6-1904-44d0-838c-4c87a9490a6b",
Name: "reduced-availability",
Description: "Durable Reduced Availability storage class.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_class": "DURABLE_REDUCED_AVAILABILITY"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "c8538397-8f15-45e3-a229-8bb349c3a98f",
Name: "coldline",
Description: "Google Cloud Storage Coldline is a very-low-cost, highly durable storage service for data archiving, online backup, and disaster recovery.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_class": "COLDLINE"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "5e6161d2-0202-48be-80c4-1006cce19b9d",
Name: "regional",
Description: "Data is stored in a narrow geographic region, redundant across availability zones with a 99.99% typical monthly availability.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_class": "REGIONAL"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "a5e8dfb5-e5ec-472a-8d36-33afcaff2fdb",
Name: "multiregional",
Description: "Data is stored geo-redundantly with >99.99% typical monthly availability.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_class": "MULTI_REGIONAL"},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
{
FieldName: "name",
Type: broker.JsonTypeString,
Details: "The name of the bucket. There is a single global namespace shared by all buckets so it MUST be unique.",
Default: "pcf_sb_${counter.next()}_${time.nano()}",
Constraints: validation.NewConstraintBuilder(). // https://cloud.google.com/storage/docs/naming
Pattern("^[a-z0-9_.-]+$").
MinLength(3).
MaxLength(222).
Build(),
},
{
FieldName: "location",
Type: broker.JsonTypeString,
Default: "US",
Details: `The location of the bucket. Object data for objects in the bucket resides in physical storage within this region. See: https://cloud.google.com/storage/docs/bucket-locations`,
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Examples("US", "EU", "southamerica-east1").
Build(),
},
{
FieldName: "force_delete",
Type: broker.JsonTypeString,
Default: "false",
Details: `Attempt to erase bucket contents before deleting bucket on deprovision.`,
Constraints: validation.NewConstraintBuilder().Enum("true", "false").Build(),
},
},
ProvisionComputedVariables: []varcontext.DefaultVariable{
{Name: "labels", Default: "${json.marshal(request.default_labels)}", Overwrite: true},
},
DefaultRoleWhitelist: roleWhitelist,
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist, "storage.objectAdmin"),
BindOutputVariables: append(accountmanagers.ServiceAccountBindOutputVariables(),
broker.BrokerVariable{
FieldName: "bucket_name",
Type: broker.JsonTypeString,
Details: "Name of the bucket this binding is for.",
Required: true,
Constraints: validation.NewConstraintBuilder(). // https://cloud.google.com/storage/docs/naming
Pattern("^[A-Za-z0-9_\\.]+$").
MinLength(3).
MaxLength(222).
Build(),
},
),
PlanVariables: []broker.BrokerVariable{
{
FieldName: "storage_class",
Type: broker.JsonTypeString,
Details: "The storage class of the bucket. See: https://cloud.google.com/storage/docs/storage-classes.",
Required: true,
},
},
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Create a nearline bucket with a service account that can create/read/list/delete the objects in it.",
PlanId: "a42c1182-d1a0-4d40-82c1-28220518b360",
ProvisionParams: map[string]interface{}{"location": "us"},
BindParams: map[string]interface{}{
"role": "storage.objectAdmin",
},
},
{
Name: "Cold Storage",
Description: "Create a coldline bucket with a service account that can create/read/list/delete the objects in it.",
PlanId: "c8538397-8f15-45e3-a229-8bb349c3a98f",
ProvisionParams: map[string]interface{}{"location": "us"},
BindParams: map[string]interface{}{
"role": "storage.objectAdmin",
},
},
{
Name: "Regional Storage",
Description: "Create a regional bucket with a service account that can create/read/list/delete the objects in it.",
PlanId: "5e6161d2-0202-48be-80c4-1006cce19b9d",
ProvisionParams: map[string]interface{}{"location": "us-west1"},
BindParams: map[string]interface{}{
"role": "storage.objectAdmin",
},
},
{
Name: "Multi-Regional Storage",
Description: "Create a multi-regional bucket with a service account that can create/read/list/delete the objects in it.",
PlanId: "a5e8dfb5-e5ec-472a-8d36-33afcaff2fdb",
ProvisionParams: map[string]interface{}{"location": "us"},
BindParams: map[string]interface{}{
"role": "storage.objectAdmin",
},
},
{
Name: "Delete even if not empty",
Description: "Sets the label sb-force-delete=true on the bucket. The broker will try to erase all contents before deleting the bucket.",
PlanId: "5e6161d2-0202-48be-80c4-1006cce19b9d",
ProvisionParams: map[string]interface{}{
"location": "us-west1",
"force_delete": "true",
},
BindParams: map[string]interface{}{
"role": "storage.objectAdmin",
},
},
},
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &StorageBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/dataflow/broker.go | pkg/providers/builtin/dataflow/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 dataflow
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
// DataflowBroker is the service-broker back-end for creating and binding Dataflow clients.
type DataflowBroker struct {
base.BrokerBase
}
// Provision is a no-op call because only service accounts need to be bound/unbound for Dataflow.
func (b *DataflowBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
return models.ServiceInstanceDetails{}, nil
}
// Deprovision is a no-op call because only service accounts need to be bound/unbound for Dataflow.
func (b *DataflowBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
return nil, 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/providers/builtin/dataflow/definition.go | pkg/providers/builtin/dataflow/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 dataflow
import (
"code.cloudfoundry.org/lager"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Dataflow service.
func ServiceDefinition() *broker.ServiceDefinition {
roleWhitelist := []string{"dataflow.viewer", "dataflow.developer"}
return &broker.ServiceDefinition{
Id: "3e897eb3-9062-4966-bd4f-85bda0f73b3d",
Name: "google-dataflow",
Description: "A managed service for executing a wide variety of data processing patterns built on Apache Beam.",
DisplayName: "Google Cloud Dataflow",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/dataflow.svg",
DocumentationUrl: "https://cloud.google.com/dataflow/docs/",
SupportUrl: "https://cloud.google.com/dataflow/docs/support",
Tags: []string{"gcp", "dataflow", "preview"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "8e956dd6-8c0f-470c-9a11-065537d81872",
Name: "default",
Description: "Dataflow default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist, "dataflow.developer"),
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
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"},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &DataflowBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/base/mixins.go | pkg/providers/builtin/base/mixins.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 base
import (
"context"
"encoding/json"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
type synchronousBase struct{}
// PollInstance does nothing but return an error because Base services are
// provisioned synchronously so this method should not be called.
func (b *synchronousBase) PollInstance(ctx context.Context, instance models.ServiceInstanceDetails) (bool, error) {
return true, brokerapi.ErrAsyncRequired
}
// ProvisionsAsync indicates if provisioning must be done asynchronously.
func (b *synchronousBase) ProvisionsAsync() bool {
return false
}
// DeprovisionsAsync indicates if deprovisioning must be done asynchronously.
func (b *synchronousBase) DeprovisionsAsync() bool {
return false
}
// AsynchronousInstanceMixin sets ProvisionAsync and DeprovisionsAsync functions
// to be true.
type AsynchronousInstanceMixin struct{}
// ProvisionsAsync indicates if provisioning must be done asynchronously.
func (b *AsynchronousInstanceMixin) ProvisionsAsync() bool {
return true
}
// DeprovisionsAsync indicates if deprovisioning must be done asynchronously.
func (b *AsynchronousInstanceMixin) DeprovisionsAsync() bool {
return true
}
// NoOpBindMixin does a no-op binding. This can be used when you still want a
// service to be bindable but nothing is required server-side to support it.
// For example, when the service requires no authentication.
type NoOpBindMixin struct{}
// Bind does a no-op bind.
func (m *NoOpBindMixin) Bind(ctx context.Context, vc *varcontext.VarContext) (map[string]interface{}, error) {
return make(map[string]interface{}), nil
}
// Unbind does a no-op unbind.
func (m *NoOpBindMixin) Unbind(ctx context.Context, instance models.ServiceInstanceDetails, creds models.ServiceBindingCredentials) error {
return nil
}
// MergedInstanceCredsMixin adds the BuildInstanceCredentials function that
// merges the OtherDetails of the bind and instance records.
type MergedInstanceCredsMixin struct{}
// BuildInstanceCredentials combines the bind credentials with the connection
// information in the instance details to get a full set of connection details.
func (b *MergedInstanceCredsMixin) BuildInstanceCredentials(ctx context.Context, bindRecord models.ServiceBindingCredentials, instanceRecord models.ServiceInstanceDetails) (*brokerapi.Binding, error) {
vc, err := varcontext.Builder().
MergeJsonObject(json.RawMessage(bindRecord.OtherDetails)).
MergeJsonObject(json.RawMessage(instanceRecord.OtherDetails)).
Build()
if err != nil {
return nil, err
}
return &brokerapi.Binding{Credentials: vc.ToMap()}, 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/providers/builtin/base/broker_base.go | pkg/providers/builtin/base/broker_base.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 base
import (
"context"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"golang.org/x/oauth2/jwt"
)
//go:generate counterfeiter . ServiceAccountManager
type ServiceAccountManager interface {
CreateCredentials(ctx context.Context, vc *varcontext.VarContext) (map[string]interface{}, error)
DeleteCredentials(ctx context.Context, creds models.ServiceBindingCredentials) error
}
// NewBrokerBase creates a new broker base and account manager it uses from the
// given settings.
func NewBrokerBase(projectId string, auth *jwt.Config, logger lager.Logger) BrokerBase {
saManager := &account_managers.ServiceAccountManager{
HttpConfig: auth,
ProjectId: projectId,
Logger: logger,
}
return BrokerBase{
AccountManager: saManager,
HttpConfig: auth,
ProjectId: projectId,
Logger: logger,
}
}
// BrokerBase is the reference bind and unbind implementation for brokers that
// bind and unbind with only Service Accounts.
type BrokerBase struct {
synchronousBase
MergedInstanceCredsMixin
AccountManager ServiceAccountManager
HttpConfig *jwt.Config
ProjectId string
Logger lager.Logger
}
// Bind creates a service account with access to the provisioned resource with
// the given instance.
func (b *BrokerBase) Bind(ctx context.Context, vc *varcontext.VarContext) (map[string]interface{}, error) {
return b.AccountManager.CreateCredentials(ctx, vc)
}
// Unbind deletes the created service account from the GCP Project.
func (b *BrokerBase) Unbind(ctx context.Context, instance models.ServiceInstanceDetails, creds models.ServiceBindingCredentials) error {
return b.AccountManager.DeleteCredentials(ctx, creds)
}
// UpdateInstanceDetails updates the ServiceInstanceDetails with the most recent state from GCP.
// This instance is a no-op method.
func (b *BrokerBase) UpdateInstanceDetails(ctx context.Context, instance *models.ServiceInstanceDetails) error {
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/pkg/providers/builtin/base/variables.go | pkg/providers/builtin/base/variables.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 base
import (
"fmt"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
)
const (
// InstanceIDKey is the key used by Instance identifier BrokerVariables.
InstanceIDKey = "instance_id"
// ZoneKey is the key used by Zone BrokerVariables.
ZoneKey = "zone"
// RegionKey is the key used by Region BrokerVariables.
RegionKey = "region"
// AuthorizedNetworkKey is the key used to define authorized networks.
AuthorizedNetworkKey = "authorized_network"
)
// UniqueArea defines an umbrella under which identifiers must be unique.
type UniqueArea string
const (
// ZoneArea indicates uniqueness per zone
ZoneArea UniqueArea = "per zone"
// RegionArea indicates uniqueness per region
RegionArea UniqueArea = "per region"
// ProjectArea indicates uniqueness per project
ProjectArea UniqueArea = "per project"
// GlobalArea indicates global uniqueness
GlobalArea UniqueArea = "globally"
)
// InstanceID creates an InstanceID broker variable with key InstanceIDKey.
// It accepts lower-case InstanceIDs with hyphens.
func InstanceID(minLength, maxLength int, uniqueArea UniqueArea) broker.BrokerVariable {
return broker.BrokerVariable{
FieldName: InstanceIDKey,
Type: broker.JsonTypeString,
Details: fmt.Sprintf("The name of the instance. The name must be unique %s.", uniqueArea),
Default: "gsb-${counter.next()}-${time.nano()}",
Constraints: validation.NewConstraintBuilder().
MinLength(minLength).
MaxLength(maxLength).
Pattern("^[a-z]([-0-9a-z]*[a-z0-9]$)*").
Build(),
}
}
// Zone creates a variable that accepts GCP zones.
func Zone(defaultLocation, supportedLocationsURL string) broker.BrokerVariable {
return broker.BrokerVariable{
FieldName: ZoneKey,
Type: broker.JsonTypeString,
Details: fmt.Sprintf("The zone to create the instance in. Supported zones can be found here: %s.", supportedLocationsURL),
Default: defaultLocation,
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Build(),
}
}
// Region creates a variable that accepts GCP regions.
func Region(defaultLocation, supportedLocationsURL string) broker.BrokerVariable {
return broker.BrokerVariable{
FieldName: RegionKey,
Type: broker.JsonTypeString,
Details: fmt.Sprintf("The region to create the instance in. Supported regions can be found here: %s.", supportedLocationsURL),
Default: defaultLocation,
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Build(),
}
}
// AuthorizedNetwork returns a variable used to attach resources to a
// user-defined network.
func AuthorizedNetwork() broker.BrokerVariable {
return broker.BrokerVariable{
FieldName: AuthorizedNetworkKey,
Type: broker.JsonTypeString,
Details: "The name of the VPC network to attach the instance to.",
Default: "default",
Constraints: validation.NewConstraintBuilder().
Examples("default", "projects/MYPROJECT/global/networks/MYNETWORK").
Build(),
}
}
| 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/providers/builtin/base/peered_network_service.go | pkg/providers/builtin/base/peered_network_service.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 base
import (
"code.cloudfoundry.org/lager"
"golang.org/x/oauth2/jwt"
)
// NewPeeredNetworkServiceBase creates a new PeeredNetworkServiceBase from the
// given settings.
func NewPeeredNetworkServiceBase(projectID string, auth *jwt.Config, logger lager.Logger) PeeredNetworkServiceBase {
return PeeredNetworkServiceBase{
HTTPConfig: auth,
DefaultProjectID: projectID,
Logger: logger,
}
}
// PeeredNetworkServiceBase is a base for services that are attached to a
// project via peered network.
type PeeredNetworkServiceBase struct {
MergedInstanceCredsMixin
AccountManager ServiceAccountManager
HTTPConfig *jwt.Config
DefaultProjectID string
Logger lager.Logger
}
| 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/providers/builtin/base/basefakes/fake_service_account_manager.go | pkg/providers/builtin/base/basefakes/fake_service_account_manager.go | // Code generated by counterfeiter. DO NOT EDIT.
package basefakes
import (
context "context"
sync "sync"
models "github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
base "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
varcontext "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
)
type FakeServiceAccountManager struct {
CreateCredentialsStub func(context.Context, *varcontext.VarContext) (map[string]interface{}, error)
createCredentialsMutex sync.RWMutex
createCredentialsArgsForCall []struct {
arg1 context.Context
arg2 *varcontext.VarContext
}
createCredentialsReturns struct {
result1 map[string]interface{}
result2 error
}
createCredentialsReturnsOnCall map[int]struct {
result1 map[string]interface{}
result2 error
}
DeleteCredentialsStub func(context.Context, models.ServiceBindingCredentials) error
deleteCredentialsMutex sync.RWMutex
deleteCredentialsArgsForCall []struct {
arg1 context.Context
arg2 models.ServiceBindingCredentials
}
deleteCredentialsReturns struct {
result1 error
}
deleteCredentialsReturnsOnCall map[int]struct {
result1 error
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeServiceAccountManager) CreateCredentials(arg1 context.Context, arg2 *varcontext.VarContext) (map[string]interface{}, error) {
fake.createCredentialsMutex.Lock()
ret, specificReturn := fake.createCredentialsReturnsOnCall[len(fake.createCredentialsArgsForCall)]
fake.createCredentialsArgsForCall = append(fake.createCredentialsArgsForCall, struct {
arg1 context.Context
arg2 *varcontext.VarContext
}{arg1, arg2})
fake.recordInvocation("CreateCredentials", []interface{}{arg1, arg2})
fake.createCredentialsMutex.Unlock()
if fake.CreateCredentialsStub != nil {
return fake.CreateCredentialsStub(arg1, arg2)
}
if specificReturn {
return ret.result1, ret.result2
}
fakeReturns := fake.createCredentialsReturns
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeServiceAccountManager) CreateCredentialsCallCount() int {
fake.createCredentialsMutex.RLock()
defer fake.createCredentialsMutex.RUnlock()
return len(fake.createCredentialsArgsForCall)
}
func (fake *FakeServiceAccountManager) CreateCredentialsCalls(stub func(context.Context, *varcontext.VarContext) (map[string]interface{}, error)) {
fake.createCredentialsMutex.Lock()
defer fake.createCredentialsMutex.Unlock()
fake.CreateCredentialsStub = stub
}
func (fake *FakeServiceAccountManager) CreateCredentialsArgsForCall(i int) (context.Context, *varcontext.VarContext) {
fake.createCredentialsMutex.RLock()
defer fake.createCredentialsMutex.RUnlock()
argsForCall := fake.createCredentialsArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeServiceAccountManager) CreateCredentialsReturns(result1 map[string]interface{}, result2 error) {
fake.createCredentialsMutex.Lock()
defer fake.createCredentialsMutex.Unlock()
fake.CreateCredentialsStub = nil
fake.createCredentialsReturns = struct {
result1 map[string]interface{}
result2 error
}{result1, result2}
}
func (fake *FakeServiceAccountManager) CreateCredentialsReturnsOnCall(i int, result1 map[string]interface{}, result2 error) {
fake.createCredentialsMutex.Lock()
defer fake.createCredentialsMutex.Unlock()
fake.CreateCredentialsStub = nil
if fake.createCredentialsReturnsOnCall == nil {
fake.createCredentialsReturnsOnCall = make(map[int]struct {
result1 map[string]interface{}
result2 error
})
}
fake.createCredentialsReturnsOnCall[i] = struct {
result1 map[string]interface{}
result2 error
}{result1, result2}
}
func (fake *FakeServiceAccountManager) DeleteCredentials(arg1 context.Context, arg2 models.ServiceBindingCredentials) error {
fake.deleteCredentialsMutex.Lock()
ret, specificReturn := fake.deleteCredentialsReturnsOnCall[len(fake.deleteCredentialsArgsForCall)]
fake.deleteCredentialsArgsForCall = append(fake.deleteCredentialsArgsForCall, struct {
arg1 context.Context
arg2 models.ServiceBindingCredentials
}{arg1, arg2})
fake.recordInvocation("DeleteCredentials", []interface{}{arg1, arg2})
fake.deleteCredentialsMutex.Unlock()
if fake.DeleteCredentialsStub != nil {
return fake.DeleteCredentialsStub(arg1, arg2)
}
if specificReturn {
return ret.result1
}
fakeReturns := fake.deleteCredentialsReturns
return fakeReturns.result1
}
func (fake *FakeServiceAccountManager) DeleteCredentialsCallCount() int {
fake.deleteCredentialsMutex.RLock()
defer fake.deleteCredentialsMutex.RUnlock()
return len(fake.deleteCredentialsArgsForCall)
}
func (fake *FakeServiceAccountManager) DeleteCredentialsCalls(stub func(context.Context, models.ServiceBindingCredentials) error) {
fake.deleteCredentialsMutex.Lock()
defer fake.deleteCredentialsMutex.Unlock()
fake.DeleteCredentialsStub = stub
}
func (fake *FakeServiceAccountManager) DeleteCredentialsArgsForCall(i int) (context.Context, models.ServiceBindingCredentials) {
fake.deleteCredentialsMutex.RLock()
defer fake.deleteCredentialsMutex.RUnlock()
argsForCall := fake.deleteCredentialsArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeServiceAccountManager) DeleteCredentialsReturns(result1 error) {
fake.deleteCredentialsMutex.Lock()
defer fake.deleteCredentialsMutex.Unlock()
fake.DeleteCredentialsStub = nil
fake.deleteCredentialsReturns = struct {
result1 error
}{result1}
}
func (fake *FakeServiceAccountManager) DeleteCredentialsReturnsOnCall(i int, result1 error) {
fake.deleteCredentialsMutex.Lock()
defer fake.deleteCredentialsMutex.Unlock()
fake.DeleteCredentialsStub = nil
if fake.deleteCredentialsReturnsOnCall == nil {
fake.deleteCredentialsReturnsOnCall = make(map[int]struct {
result1 error
})
}
fake.deleteCredentialsReturnsOnCall[i] = struct {
result1 error
}{result1}
}
func (fake *FakeServiceAccountManager) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.createCredentialsMutex.RLock()
defer fake.createCredentialsMutex.RUnlock()
fake.deleteCredentialsMutex.RLock()
defer fake.deleteCredentialsMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeServiceAccountManager) 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 _ base.ServiceAccountManager = new(FakeServiceAccountManager)
| 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/providers/builtin/filestore/broker.go | pkg/providers/builtin/filestore/broker.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 filestore
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
filestore "google.golang.org/api/file/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)
const (
// DefaultFileshareName is the default created for fileshares.
DefaultFileshareName = "filestore"
)
// NewInstanceInformation creates instance information from an instance
func NewInstanceInformation(instance filestore.Instance) (*InstanceInformation, error) {
if len(instance.Networks) == 0 {
return nil, errors.New("no networks were defined on the instance")
}
network := instance.Networks[0]
if len(network.IpAddresses) == 0 {
return nil, errors.New("no IP addresses were defined on the instance")
}
ip := network.IpAddresses[0]
if len(instance.FileShares) == 0 {
return nil, errors.New("no file shares were defined on the instance")
}
share := instance.FileShares[0]
return &InstanceInformation{
Network: network.Network,
ReservedIPRange: network.ReservedIpRange,
IPAddress: ip,
FileShareName: share.Name,
CapacityGB: share.CapacityGb,
URI: fmt.Sprintf("nfs://%s/%s", ip, share.Name),
}, nil
}
// InstanceInformation holds the details needed to get a Filestore instance
// once it's been created.
type InstanceInformation struct {
Network string `json:"authorized_network"`
ReservedIPRange string `json:"reserved_ip_range"`
IPAddress string `json:"ip_address"`
FileShareName string `json:"file_share_name"`
CapacityGB int64 `json:"capacity_gb"`
URI string `json:"uri"`
}
// Broker is the back-end for creating and binding to Google Cloud Filestores.
type Broker struct {
base.PeeredNetworkServiceBase
base.NoOpBindMixin
base.AsynchronousInstanceMixin
}
var _ (broker.ServiceProvider) = (*Broker)(nil)
// Provision implements ServiceProvider.Provision.
func (b *Broker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
details := models.ServiceInstanceDetails{
Name: provisionContext.GetString(base.InstanceIDKey),
Location: provisionContext.GetString(base.ZoneKey),
}
instance := &filestore.Instance{
Labels: provisionContext.GetStringMapString("labels"),
Tier: provisionContext.GetString("tier"),
FileShares: []*filestore.FileShareConfig{
{
Name: DefaultFileshareName,
CapacityGb: int64(provisionContext.GetInt("capacity_gb")),
},
},
Networks: []*filestore.NetworkConfig{
{
Modes: []string{
provisionContext.GetString("address_mode"),
},
Network: provisionContext.GetString(base.AuthorizedNetworkKey),
},
},
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
client, err := b.createClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
op, err := client.Projects.Locations.Instances.
Create(b.parentPath(details), instance).
InstanceId(details.Name).
Do()
if err != nil {
return models.ServiceInstanceDetails{}, err
}
details.OperationType = models.ProvisionOperationType
details.OperationId = op.Name
return details, nil
}
// Deprovision implements ServiceProvider.Deprovision.
func (b *Broker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
client, err := b.createClient(ctx)
if err != nil {
return nil, err
}
op, err := client.Projects.Locations.Instances.Delete(b.instancePath(instance)).Do()
if err != nil {
// Mark things that have been deleted out of band as gone.
if gerr, ok := err.(*googleapi.Error); ok {
if gerr.Code == http.StatusNotFound || gerr.Code == http.StatusGone {
return nil, nil
}
}
return nil, err
}
return &op.Name, nil
}
func (b *Broker) createClient(ctx context.Context) (*filestore.Service, error) {
co := option.WithUserAgent(utils.CustomUserAgent)
ct := option.WithTokenSource(b.HTTPConfig.TokenSource(ctx))
c, err := filestore.NewService(ctx, co, ct)
if err != nil {
return nil, fmt.Errorf("couldn't instantiate API client: %s", err)
}
return c, nil
}
func (b *Broker) parentPath(instanceDetails models.ServiceInstanceDetails) string {
return fmt.Sprintf("projects/%s/locations/%s", b.DefaultProjectID, instanceDetails.Location)
}
func (b *Broker) instancePath(instanceDetails models.ServiceInstanceDetails) string {
return fmt.Sprintf("%s/instances/%s", b.parentPath(instanceDetails), instanceDetails.Name)
}
// PollInstance implements ServiceProvider.PollInstance
func (b *Broker) PollInstance(ctx context.Context, instance models.ServiceInstanceDetails) (done bool, err error) {
if instance.OperationType == "" {
return false, errors.New("couldn't find any pending operations")
}
client, err := b.createClient(ctx)
if err != nil {
return false, err
}
op, err := client.Projects.Locations.Operations.Get(instance.OperationId).Do()
if op != nil {
done = op.Done
}
return done, err
}
// UpdateInstanceDetails updates the ServiceInstanceDetails with the most recent state from GCP.
// This instance is a no-op method.
func (b *Broker) UpdateInstanceDetails(ctx context.Context, instance *models.ServiceInstanceDetails) error {
client, err := b.createClient(ctx)
if err != nil {
return err
}
actualInstance, err := client.Projects.Locations.Instances.Get(b.instancePath(*instance)).Do()
if err != nil {
return err
}
instanceInfo, err := NewInstanceInformation(*actualInstance)
if err != nil {
return err
}
return instance.SetOtherDetails(*instanceInfo)
}
| 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/providers/builtin/filestore/definition.go | pkg/providers/builtin/filestore/definition.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 filestore
import (
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Firestore service.
func ServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "494eb82e-c4ca-4bed-871d-9c3f02f66e01",
Name: "google-filestore",
Description: "Fully managed NFS file storage with predictable performance.",
DisplayName: "Google Cloud Filestore",
// Filestore doesn't have a hex logo so we'll copy storage's.
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/storage.svg",
DocumentationUrl: "https://cloud.google.com/filestore/docs/",
SupportUrl: "https://cloud.google.com/filestore/docs/getting-support",
Tags: []string{"gcp", "filestore", "nfs"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "e4c83975-e60f-43cf-afde-ebec573c6c2e",
Name: "default",
Description: "Filestore default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
base.InstanceID(1, 63, base.ZoneArea),
base.Zone("us-west1-a", "https://cloud.google.com/filestore/docs/regions"),
{
FieldName: "tier",
Default: "STANDARD",
Type: broker.JsonTypeString,
Details: "The performance tier.",
Enum: map[interface{}]string{
"STANDARD": "Standard Tier: 100 MB/s reads, 5000 IOPS",
"PREMIUM": "Premium Tier: 1.2 GB/s reads, 60000 IOPS",
},
},
{
FieldName: "authorized_network",
Type: broker.JsonTypeString,
Details: "The name of the network to attach the instance to.",
Default: "default",
},
{
FieldName: "address_mode",
Default: "MODE_IPV4",
Type: broker.JsonTypeString,
Details: "The address mode of the service.",
Enum: map[interface{}]string{
"MODE_IPV4": "IPV4 Addressed",
},
},
{
FieldName: "capacity_gb",
Type: broker.JsonTypeInteger,
Details: "The capacity of the Filestore. Standard minimum is 1TiB and Premium is minimum 2.5TiB.",
Default: 1024,
},
},
ProvisionComputedVariables: []varcontext.DefaultVariable{
{Name: "labels", Default: "${json.marshal(request.default_labels)}", Overwrite: true},
},
BindInputVariables: []broker.BrokerVariable{},
BindOutputVariables: []broker.BrokerVariable{
{
FieldName: "authorized_network",
Type: broker.JsonTypeString,
Details: "Name of the VPC network the instance is attached to.",
},
{
FieldName: "reserved_ip_range",
Type: broker.JsonTypeString,
Details: "Range of IP addresses reserved for the instance.",
},
{
FieldName: "ip_address",
Type: broker.JsonTypeString,
Details: "IP address of the service.",
},
{
FieldName: "file_share_name",
Type: broker.JsonTypeString,
Details: "Name of the share.",
},
{
FieldName: "capacity_gb",
Type: broker.JsonTypeInteger,
Details: "Capacity of the share in GiB.",
},
{
FieldName: "uri",
Type: broker.JsonTypeString,
Details: "URI of the instance.",
},
},
BindComputedVariables: []varcontext.DefaultVariable{},
Examples: []broker.ServiceExample{
{
Name: "Standard",
Description: "Creates a standard Filestore.",
PlanId: "e4c83975-e60f-43cf-afde-ebec573c6c2e",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
{
Name: "Premium",
Description: "Creates a premium Filestore.",
PlanId: "e4c83975-e60f-43cf-afde-ebec573c6c2e",
ProvisionParams: map[string]interface{}{
"tier": "PREMIUM",
"capacity_gb": 2560,
},
BindParams: map[string]interface{}{},
},
},
ProviderBuilder: func(projectID string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewPeeredNetworkServiceBase(projectID, auth, logger)
return &Broker{PeeredNetworkServiceBase: bb}
},
IsBuiltin: 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/providers/builtin/redis/broker.go | pkg/providers/builtin/redis/broker.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 redis
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/net/context"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
redis "google.golang.org/api/redis/v1"
)
// Broker is the service-broker back-end for creating and binding Redis services.
type Broker struct {
base.PeeredNetworkServiceBase
base.NoOpBindMixin
base.AsynchronousInstanceMixin
}
// NewInstanceInformation creates instance information from an instance
func NewInstanceInformation(instance redis.Instance) InstanceInformation {
return InstanceInformation{
Network: instance.AuthorizedNetwork,
ReservedIPRange: instance.ReservedIpRange,
RedisVersion: instance.RedisVersion,
MemorySizeGb: instance.MemorySizeGb,
Host: instance.Host,
Port: instance.Port,
URI: fmt.Sprintf("redis://%s:%d", instance.Host, instance.Port),
}
}
// InstanceInformation holds the details needed to connect to a Redis instance after it has been provisioned
type InstanceInformation struct {
// Info for admins to diagnose connection issues
Network string `json:"authorized_network"`
ReservedIPRange string `json:"reserved_ip_range"`
// Info for developers to diagnose client issues
RedisVersion string `json:"redis_version"`
MemorySizeGb int64 `json:"memory_size_gb"`
// Connection info
Host string `json:"host"`
Port int64 `json:"port"`
URI string `json:"uri"`
}
// Provision creates a new Redis instance from the settings in the user-provided details and service plan.
func (b *Broker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
details := models.ServiceInstanceDetails{
Name: provisionContext.GetString(base.InstanceIDKey),
Location: provisionContext.GetString(base.RegionKey),
}
instance := &redis.Instance{
Labels: provisionContext.GetStringMapString("labels"),
Tier: provisionContext.GetString("tier"),
MemorySizeGb: int64(provisionContext.GetInt("memory_size_gb")),
AuthorizedNetwork: provisionContext.GetString(base.AuthorizedNetworkKey),
}
// The API only accepts fully qualified networks.
// If the user doesn't specify, assume they want the one for the default project.
if !strings.Contains(instance.AuthorizedNetwork, "/") {
instance.AuthorizedNetwork = fmt.Sprintf("projects/%s/global/networks/%s", b.DefaultProjectID, instance.AuthorizedNetwork)
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
client, err := b.createClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
op, err := client.Projects.Locations.Instances.
Create(b.parentPath(details), instance).
InstanceId(details.Name).
Do()
if err != nil {
return models.ServiceInstanceDetails{}, err
}
details.OperationType = models.ProvisionOperationType
details.OperationId = op.Name
return details, nil
}
// Deprovision deletes the Redis instance with the given instance ID
func (b *Broker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
client, err := b.createClient(ctx)
if err != nil {
return nil, err
}
op, err := client.Projects.Locations.Instances.Delete(b.instancePath(instance)).Do()
if err != nil {
// Mark things that have been deleted out of band as gone.
if gerr, ok := err.(*googleapi.Error); ok {
if gerr.Code == http.StatusNotFound || gerr.Code == http.StatusGone {
return nil, nil
}
}
return nil, err
}
return &op.Name, nil
}
func (b *Broker) parentPath(instanceDetails models.ServiceInstanceDetails) string {
return fmt.Sprintf("projects/%s/locations/%s", b.DefaultProjectID, instanceDetails.Location)
}
func (b *Broker) instancePath(instanceDetails models.ServiceInstanceDetails) string {
return fmt.Sprintf("%s/instances/%s", b.parentPath(instanceDetails), instanceDetails.Name)
}
func (b *Broker) createClient(ctx context.Context) (*redis.Service, error) {
co := option.WithUserAgent(utils.CustomUserAgent)
ct := option.WithTokenSource(b.HTTPConfig.TokenSource(ctx))
c, err := redis.NewService(ctx, co, ct)
if err != nil {
return nil, fmt.Errorf("couldn't instantiate API client: %s", err)
}
return c, nil
}
// PollInstance implements ServiceProvider.PollInstance
func (b *Broker) PollInstance(ctx context.Context, instance models.ServiceInstanceDetails) (done bool, err error) {
if instance.OperationType == "" {
return false, errors.New("couldn't find any pending operations")
}
client, err := b.createClient(ctx)
if err != nil {
return false, err
}
op, err := client.Projects.Locations.Operations.Get(instance.OperationId).Do()
if op != nil {
done = op.Done
}
return done, err
}
// UpdateInstanceDetails updates the ServiceInstanceDetails with the most recent state from GCP.
// This instance is a no-op method.
func (b *Broker) UpdateInstanceDetails(ctx context.Context, instance *models.ServiceInstanceDetails) error {
client, err := b.createClient(ctx)
if err != nil {
return err
}
actualInstance, err := client.Projects.Locations.Instances.Get(b.instancePath(*instance)).Do()
if err != nil {
return err
}
return instance.SetOtherDetails(NewInstanceInformation(*actualInstance))
}
| 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/providers/builtin/redis/definition.go | pkg/providers/builtin/redis/definition.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 redis
import (
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
func ServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "3ea92b54-838c-4fe1-b75d-9bda513380aa",
Name: "google-memorystore-redis",
Description: "Creates and manages Redis instances on the Google Cloud Platform.",
DisplayName: "Google Cloud Memorystore for Redis API",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/cache.svg",
DocumentationUrl: "https://cloud.google.com/memorystore/docs/redis",
SupportUrl: "https://cloud.google.com/memorystore/docs/redis/support",
Tags: []string{"gcp", "memorystore", "redis"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "df10762e-6ef1-44e3-84c2-07e9358ceb1f",
Name: "default",
Description: "Lets you chose your own values for all properties.",
Free: brokerapi.FreeValue(false),
},
ProvisionOverrides: map[string]interface{}{},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "dd1923b6-ac26-4697-83d6-b3a0c05c2c94",
Name: "basic",
Description: "Provides a standalone Redis instance. Use this tier for applications that require a simple Redis cache.",
Free: brokerapi.FreeValue(false),
},
ProvisionOverrides: map[string]interface{}{"service_tier": "BASIC"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "41771881-b456-4940-9081-34b6424744c6",
Name: "standard_ha",
Description: "Provides a highly available Redis instance.",
Free: brokerapi.FreeValue(false),
},
ProvisionOverrides: map[string]interface{}{"service_tier": "STANDARD_HA"},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
base.InstanceID(1, 40, base.ProjectArea),
base.AuthorizedNetwork(),
base.Region("us-east1", "https://cloud.google.com/memorystore/docs/redis/regions"),
{
FieldName: "memory_size_gb",
Type: broker.JsonTypeInteger,
Details: "Redis memory size in GiB.",
Default: 4,
},
{
FieldName: "tier",
Type: broker.JsonTypeString,
Details: "The performance tier.",
Default: "BASIC",
Enum: map[interface{}]string{
"BASIC": "Standalone instance, good for caching.",
"STANDARD_HA": "Highly available primary/replica, good for databases.",
},
},
},
ProvisionComputedVariables: []varcontext.DefaultVariable{
{Name: "labels", Default: "${json.marshal(request.default_labels)}", Overwrite: true},
},
BindInputVariables: []broker.BrokerVariable{},
BindOutputVariables: []broker.BrokerVariable{
{
FieldName: "authorized_network",
Type: broker.JsonTypeString,
Details: "Name of the VPC network the instance is attached to.",
},
{
FieldName: "reserved_ip_range",
Type: broker.JsonTypeString,
Details: "Range of IP addresses reserved for the instance.",
},
{
FieldName: "redis_version",
Type: broker.JsonTypeString,
Details: "The version of Redis software.",
},
{
FieldName: "memory_size_gb",
Type: broker.JsonTypeInteger,
Details: "Redis memory size in GiB.",
},
{
FieldName: "host",
Type: broker.JsonTypeString,
Details: "Hostname or IP address of the exposed Redis endpoint used by clients to connect to the service.",
},
{
FieldName: "port",
Type: broker.JsonTypeInteger,
Details: "The port number of the exposed Redis endpoint.",
},
{
FieldName: "uri",
Type: broker.JsonTypeString,
Details: "URI of the instance.",
},
},
PlanVariables: []broker.BrokerVariable{},
Examples: []broker.ServiceExample{
{
Name: "Standard Redis Configuration",
Description: "Create a Redis instance with standard service tier.",
PlanId: "dd1923b6-ac26-4697-83d6-b3a0c05c2c94",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
{
Name: "HA Redis Configuration",
Description: "Create a Redis instance with high availability.",
PlanId: "41771881-b456-4940-9081-34b6424744c6",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
},
ProviderBuilder: func(projectID string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
return &Broker{
PeeredNetworkServiceBase: base.NewPeeredNetworkServiceBase(projectID, auth, logger),
}
},
IsBuiltin: 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/providers/builtin/spanner/broker.go | pkg/providers/builtin/spanner/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 spanner
import (
"context"
"fmt"
googlespanner "cloud.google.com/go/spanner/admin/instance/apiv1"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"google.golang.org/api/option"
instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1"
)
// SpannerBroker is the service-broker back-end for creating Spanner databases
// and accounts.
type SpannerBroker struct {
base.BrokerBase
}
// InstanceInformation holds the details needed to connect to a Spanner instance
// after it has been provisioned.
type InstanceInformation struct {
InstanceId string `json:"instance_id"`
}
// Provision creates a new Spanner instance from the settings in the user-provided details and service plan.
func (s *SpannerBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
// create instance provision request
instanceName := provisionContext.GetString("name")
instanceLocation := fmt.Sprintf("projects/%s/instanceConfigs/%s", s.ProjectId, provisionContext.GetString("location"))
creationRequest := instancepb.CreateInstanceRequest{
Parent: "projects/" + s.ProjectId,
InstanceId: instanceName,
Instance: &instancepb.Instance{
Name: s.qualifiedInstanceName(instanceName),
DisplayName: provisionContext.GetString("display_name"),
NodeCount: int32(provisionContext.GetInt("num_nodes")),
Config: instanceLocation,
Labels: provisionContext.GetStringMapString("labels"),
},
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
// Make request
client, err := s.createAdminClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
op, err := client.CreateInstance(ctx, &creationRequest)
if err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error creating instance: %s", err)
}
// save off instance information
ii := InstanceInformation{
InstanceId: instanceName,
}
id := models.ServiceInstanceDetails{
Name: instanceName,
Url: "",
Location: instanceLocation,
OperationType: models.ProvisionOperationType,
OperationId: op.Name(),
}
if err := id.SetOtherDetails(ii); err != nil {
return models.ServiceInstanceDetails{}, err
}
return id, nil
}
// PollInstance gets the last operation for this instance and polls its status.
func (s *SpannerBroker) PollInstance(ctx context.Context, instance models.ServiceInstanceDetails) (bool, error) {
if instance.OperationType == models.ClearOperationType {
return false, fmt.Errorf("No pending operations could be found for this Spanner instance.")
}
if instance.OperationType != models.ProvisionOperationType {
return false, fmt.Errorf("Couldn't poll Spanner instance, unknown operation type: %s", instance.OperationType)
}
client, err := s.createAdminClient(ctx)
if err != nil {
return false, err
}
// From https://godoc.org/cloud.google.com/go/spanner/admin/instance/apiv1#CreateInstanceOperation.Poll
spannerOp := client.CreateInstanceOperation(instance.OperationId)
_, err = spannerOp.Poll(ctx)
done := spannerOp.Done()
switch {
case err != nil && !done: // There was a failure polling
return false, fmt.Errorf("Error checking operation status: %s", err)
case err != nil && done: // The operation completed in error
return true, fmt.Errorf("Error provisioning instance: %v", err)
case err == nil && done: // The operation was successful
return true, nil
default: // The operation hasn't completed yet
return false, nil
}
}
// Deprovision deletes the Spanner instance associated with the given instance.
func (s *SpannerBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
client, err := s.createAdminClient(ctx)
if err != nil {
return nil, err
}
// delete instance
err = client.DeleteInstance(ctx, &instancepb.DeleteInstanceRequest{
Name: s.qualifiedInstanceName(instance.Name),
})
if err != nil {
return nil, fmt.Errorf("Error deleting instance: %s", err)
}
return nil, nil
}
// ProvisionsAsync indicates that Spanner uses asynchronous provisioning
func (s *SpannerBroker) ProvisionsAsync() bool {
return true
}
// qualifiedInstanceName gets the fully qualified instance name with
// regards to the project id.
func (s *SpannerBroker) qualifiedInstanceName(instanceName string) string {
return fmt.Sprintf("projects/%s/instances/%s", s.ProjectId, instanceName)
}
func (s *SpannerBroker) createAdminClient(ctx context.Context) (*googlespanner.InstanceAdminClient, error) {
co := option.WithUserAgent(utils.CustomUserAgent)
ct := option.WithTokenSource(s.HttpConfig.TokenSource(ctx))
client, err := googlespanner.NewInstanceAdminClient(ctx, co, ct)
if err != nil {
return nil, fmt.Errorf("Couldn't instantiate Spanner API client: %s", 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/providers/builtin/spanner/definition.go | pkg/providers/builtin/spanner/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 spanner
import (
"code.cloudfoundry.org/lager"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Spanner service.
func ServiceDefinition() *broker.ServiceDefinition {
roleWhitelist := []string{
"spanner.databaseAdmin",
"spanner.databaseReader",
"spanner.databaseUser",
"spanner.viewer",
}
return &broker.ServiceDefinition{
Id: "51b3e27e-d323-49ce-8c5f-1211e6409e82",
Name: "google-spanner",
Description: "The first horizontally scalable, globally consistent, relational database service.",
DisplayName: "Google Spanner",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/spanner.svg",
DocumentationUrl: "https://cloud.google.com/spanner/",
SupportUrl: "https://cloud.google.com/spanner/docs/support",
Tags: []string{"gcp", "spanner"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "44828436-cfbd-47ae-b4bc-48854564347b",
Name: "sandbox",
Description: "Useful for testing, not eligible for SLA.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"num_nodes": "1"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "0752b1ad-a784-4dcc-96eb-64149089a1c9",
Name: "minimal-production",
Description: "A minimal production level Spanner setup eligible for 99.99% SLA. Each node can provide up to 10,000 QPS of reads or 2,000 QPS of writes (writing single rows at 1KB data per row), and 2 TiB storage.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"num_nodes": "3"},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
{
FieldName: "name",
Type: broker.JsonTypeString,
Details: "A unique identifier for the instance, which cannot be changed after the instance is created.",
Default: "pcf-sb-${counter.next()}-${time.nano()}",
Constraints: validation.NewConstraintBuilder().
MinLength(6).
MaxLength(30).
Pattern("^[a-z][-a-z0-9]*[a-z0-9]$").
Build(),
},
{
FieldName: "display_name",
Type: broker.JsonTypeString,
Details: "The name of this instance configuration as it appears in UIs.",
Default: "${name}",
Constraints: validation.NewConstraintBuilder().
MinLength(4).
MaxLength(30).
Build(),
},
{
FieldName: "location",
Type: broker.JsonTypeString,
Default: "regional-us-central1",
Details: `A configuration for a Cloud Spanner instance.
Configurations define the geographic placement of nodes and their replication and are slightly different from zones.
There are single region configurations, multi-region configurations, and multi-continent configurations.
See the instance docs https://cloud.google.com/spanner/docs/instances for a list of configurations.`,
Constraints: validation.NewConstraintBuilder().
Examples("regional-asia-east1", "nam3", "nam-eur-asia1").
Pattern("^[a-z][-a-z0-9]*[a-z0-9]$").
Build(),
},
},
ProvisionComputedVariables: []varcontext.DefaultVariable{
{Name: "labels", Default: "${json.marshal(request.default_labels)}", Overwrite: true},
},
DefaultRoleWhitelist: roleWhitelist,
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist, "spanner.databaseUser"),
BindOutputVariables: append(accountmanagers.ServiceAccountBindOutputVariables(),
broker.BrokerVariable{
FieldName: "instance_id",
Type: broker.JsonTypeString,
Details: "Name of the Spanner instance the account can connect to.",
Required: true,
Constraints: validation.NewConstraintBuilder().
MinLength(6).
MaxLength(30).
Pattern("^[a-z][-a-z0-9]*[a-z0-9]$").
Build(),
},
),
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
PlanVariables: []broker.BrokerVariable{
{
FieldName: "num_nodes",
Type: broker.JsonTypeString,
Details: "Number of nodes, a minimum of 3 nodes is recommended for production environments. See: https://cloud.google.com/spanner/pricing for more information.",
Default: "1",
Required: true,
},
},
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Create a sandbox environment with a database admin account.",
PlanId: "44828436-cfbd-47ae-b4bc-48854564347b",
ProvisionParams: map[string]interface{}{"name": "auth-database"},
BindParams: map[string]interface{}{"role": "spanner.databaseAdmin"},
},
{
Name: "99.999% availability",
Description: "Create a spanner instance spanning North America.",
PlanId: "44828436-cfbd-47ae-b4bc-48854564347b",
ProvisionParams: map[string]interface{}{"name": "auth-database", "location": "nam3"},
BindParams: map[string]interface{}{"role": "spanner.databaseAdmin"},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &SpannerBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/cloudsql/postgres-vpc-definition.go | pkg/providers/builtin/cloudsql/postgres-vpc-definition.go | package cloudsql
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
)
const postgresVPCID = "c90ea118-605a-47e8-8f63-57fc09c113f1"
// PostgresVPCServiceDefinition creates a new ServiceDefinition object for the
// Postgres service on a VPC.
func PostgresVPCServiceDefinition() *broker.ServiceDefinition {
definition := buildDatabase(cloudSQLOptions{
DatabaseType: postgresDatabaseType,
CustomizableActivationPolicy: false,
AdminControlsTier: false,
AdminControlsMaxDiskSize: false,
VPCNetwork: true,
})
definition.Id = postgresVPCID
definition.Name = "google-cloudsql-postgres-vpc"
definition.Plans = []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "60f0b6c0-c48f-4f84-baab-57836611e013",
Name: "default",
Description: "PostgreSQL attached to a VPC",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
}
definition.Examples = []broker.ServiceExample{
{
Name: "Dedicated Machine Sandbox",
Description: "A low end PostgreSQL sandbox that uses a dedicated machine.",
PlanId: "60f0b6c0-c48f-4f84-baab-57836611e013",
ProvisionParams: map[string]interface{}{
"tier": "db-custom-1-3840",
"backups_enabled": "false",
"disk_size": "25",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
{
Name: "HA Instance",
Description: "A regionally available database with automatic failover.",
PlanId: "60f0b6c0-c48f-4f84-baab-57836611e013",
ProvisionParams: map[string]interface{}{
"tier": "db-custom-1-3840",
"backups_enabled": "true",
"disk_size": "25",
"availability_type": "REGIONAL",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
}
return definition
}
| 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/providers/builtin/cloudsql/broker.go | pkg/providers/builtin/cloudsql/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 cloudsql
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"context"
"code.cloudfoundry.org/lager"
googleapi "google.golang.org/api/googleapi"
googlecloudsql "google.golang.org/api/sqladmin/v1beta4"
sqladmin "google.golang.org/api/sqladmin/v1beta4"
)
const (
secondGenPricingPlan string = "PER_USE"
postgresDefaultVersion string = "POSTGRES_11"
mySqlSecondGenDefaultVersion string = "MYSQL_5_7"
mySQLURIFormat = ""
)
// CloudSQLBroker is the service-broker back-end for creating and binding CloudSQL instances.
type CloudSQLBroker struct {
base.BrokerBase
uriFormat string
}
// InstanceInformation holds the details needed to bind a service account to a CloudSQL instance after it has been provisioned.
type InstanceInformation struct {
InstanceName string `json:"instance_name"`
DatabaseName string `json:"database_name"`
Host string `json:"host"`
Region string `json:"region"`
LastMasterOperationId string `json:"last_master_operation_id"`
}
// Provision creates a new CloudSQL instance from the settings in the user-provided details and service plan.
func (b *CloudSQLBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
di, ii, err := createProvisionRequest(provisionContext)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
// init sqladmin service
sqlService, err := b.createClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
// make insert request
op, err := sqlService.Instances.Insert(b.ProjectId, di).Do()
if err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error creating new CloudSQL instance: %s", err)
}
b.Logger.Debug("updating details", lager.Data{"from": "{}", "to": ii})
id := models.ServiceInstanceDetails{
Name: di.Name,
OperationType: models.ProvisionOperationType,
OperationId: op.Name,
}
if err := id.SetOtherDetails(ii); err != nil {
return models.ServiceInstanceDetails{}, err
}
return id, nil
}
func createProvisionRequest(vars *varcontext.VarContext) (*googlecloudsql.DatabaseInstance, *InstanceInformation, error) {
// set up database information
di := createInstanceRequest(vars)
// Set up instance information
ii := InstanceInformation{
InstanceName: di.Name,
DatabaseName: vars.GetString("database_name"),
}
return di, &ii, vars.Error()
}
func varctxGetAcls(vars *varcontext.VarContext) []*googlecloudsql.AclEntry {
openAcls := []*googlecloudsql.AclEntry{}
authorizedNetworkCsv := vars.GetString("authorized_networks")
if authorizedNetworkCsv == "" {
return openAcls
}
for _, v := range strings.Split(authorizedNetworkCsv, ",") {
openAcls = append(openAcls, &googlecloudsql.AclEntry{Value: v})
}
return openAcls
}
func createInstanceRequest(vars *varcontext.VarContext) *googlecloudsql.DatabaseInstance {
// Split and parse DatabaseFlags
databaseFlags := parseDatabaseFlags(vars.GetString("database_flags"))
autoResize := vars.GetBool("auto_resize")
ipConfiguration := googlecloudsql.IpConfiguration{
RequireSsl: true,
Ipv4Enabled: true,
AuthorizedNetworks: varctxGetAcls(vars),
}
if privateNetwork := vars.GetString("private_network"); privateNetwork != "" {
ipConfiguration = googlecloudsql.IpConfiguration{
Ipv4Enabled: false,
RequireSsl: true,
PrivateNetwork: privateNetwork,
ForceSendFields: []string{"Ipv4Enabled"},
}
}
// set up instance resource
// https://github.com/googleapis/google-api-go-client/blob/master/sqladmin/v1beta4/sqladmin-gen.go#L647
return &googlecloudsql.DatabaseInstance{
Name: vars.GetString("instance_name"),
DatabaseVersion: vars.GetString("version"),
Region: vars.GetString("region"),
Settings: &googlecloudsql.Settings{
AvailabilityType: vars.GetString("availability_type"),
BackupConfiguration: &googlecloudsql.BackupConfiguration{
Enabled: vars.GetBool("backups_enabled"),
StartTime: vars.GetString("backup_start_time"),
BinaryLogEnabled: vars.GetBool("binlog"),
},
DatabaseFlags: databaseFlags,
IpConfiguration: &ipConfiguration,
Tier: vars.GetString("tier"),
DataDiskSizeGb: int64(vars.GetInt("disk_size")),
LocationPreference: &googlecloudsql.LocationPreference{
Zone: vars.GetString("zone"),
},
DataDiskType: vars.GetString("disk_type"),
MaintenanceWindow: &googlecloudsql.MaintenanceWindow{
Day: int64(vars.GetInt("maintenance_window_day")),
Hour: int64(vars.GetInt("maintenance_window_hour")),
UpdateTrack: "stable",
ForceSendFields: []string{"Day", "Hour"},
},
PricingPlan: secondGenPricingPlan,
ActivationPolicy: vars.GetString("activation_policy"),
StorageAutoResize: &autoResize,
StorageAutoResizeLimit: int64(vars.GetInt("auto_resize_limit")),
UserLabels: vars.GetStringMapString("labels"),
},
}
}
func parseDatabaseFlags(flagsvar string) []*googlecloudsql.DatabaseFlags {
databaseFlags := []*googlecloudsql.DatabaseFlags{}
// Return empty DatabaseFlags when none is defined
if flagsvar == "" {
return databaseFlags
}
// Get each separate flag
flags := strings.Split(flagsvar, ",")
// Separate the flags into name and value
for _, f := range flags {
flag := strings.Split(f, "=")
databaseFlags = append(databaseFlags, &googlecloudsql.DatabaseFlags{
Name: flag[0],
Value: flag[1],
ForceSendFields: []string{"Value"},
})
}
return databaseFlags
}
// Bind creates a new username, password, and set of ssl certs for the given instance.
// The function may be slow to return because CloudSQL operations are asynchronous.
// The default CF service broker timeout may need to be raised to 90 or 120 seconds to accommodate the long bind time.
func (b *CloudSQLBroker) Bind(ctx context.Context, vc *varcontext.VarContext) (map[string]interface{}, error) {
// get context before trying to create anything to catch errors early
combinedCreds := varcontext.Builder()
useJdbcFormat := vc.GetBool("jdbc_uri_format")
if err := vc.Error(); err != nil {
return nil, err
}
// Create the service account
saCreds, err := b.BrokerBase.Bind(ctx, vc)
if err != nil {
return saCreds, err
}
combinedCreds.MergeMap(saCreds)
sqlCreds, err := b.createSqlCredentials(ctx, vc)
if err != nil {
return saCreds, err
}
combinedCreds.MergeMap(sqlCreds)
uriPrefix := ""
if useJdbcFormat {
uriPrefix = "jdbc:"
}
combinedCreds.MergeMap(map[string]interface{}{"UriPrefix": uriPrefix})
return combinedCreds.BuildMap()
}
func (b *CloudSQLBroker) BuildInstanceCredentials(ctx context.Context, bindRecord models.ServiceBindingCredentials, instanceRecord models.ServiceInstanceDetails) (*brokerapi.Binding, error) {
creds, err := varcontext.Builder().
MergeJsonObject(json.RawMessage(bindRecord.OtherDetails)).
MergeJsonObject(json.RawMessage(instanceRecord.OtherDetails)).
MergeEvalResult("uri", b.uriFormat, varcontext.TypeString).
BuildMap()
if err != nil {
return nil, err
}
return &brokerapi.Binding{Credentials: creds}, nil
}
// Unbind deletes the database user, service account and invalidates the ssl certs associated with this binding.
// It returns early to make an unbind fail if any subcommand fails.
// -> It is possible that the deletion of a postgres sql user fails because of depending objects in the db.
// In that case, the service account should not be deleted (BrokerBase.Unbind) because the users would not
// be able to connect to the db anymore.
// Terraform handles the issue in a similar way.
func (b *CloudSQLBroker) Unbind(ctx context.Context, instance models.ServiceInstanceDetails, binding models.ServiceBindingCredentials) error {
if err := b.deleteSqlSslCert(ctx, binding, instance); err != nil {
return err
}
if err := b.deleteSqlUserAccount(ctx, binding, instance); err != nil {
return err
}
if err := b.BrokerBase.Unbind(ctx, instance, binding); err != nil {
return err
}
return nil
}
// PollInstance gets the last operation for this instance and checks its status.
func (b *CloudSQLBroker) PollInstance(ctx context.Context, instance models.ServiceInstanceDetails) (bool, error) {
b.Logger.Info("PollInstance", lager.Data{
"instance": instance.Name,
"operation_type": instance.OperationType,
"operation_id": instance.OperationId,
})
if instance.OperationType == "" {
return false, errors.New("Couldn't find any pending operations for this CloudSQL instance.")
}
result, err := b.pollOperation(ctx, instance.OperationId)
if result == false || err != nil {
return result, err
}
if instance.OperationType == models.ProvisionOperationType {
// Update the instance information from the server side before
// creating the database. The modification happens _only_ to
// this instance of the details and is not persisted to the db.
if err := b.UpdateInstanceDetails(ctx, &instance); err != nil {
return true, err
}
return true, b.createDatabase(ctx, &instance)
}
return true, nil
}
// refreshServiceInstanceDetails fetches the settings for the instance from GCP
// and upates the provided instance with the refreshed info.
func (b *CloudSQLBroker) UpdateInstanceDetails(ctx context.Context, instance *models.ServiceInstanceDetails) error {
var instanceInfo InstanceInformation
if err := instance.GetOtherDetails(&instanceInfo); err != nil {
return err
}
client, err := b.createClient(ctx)
if err != nil {
return err
}
clouddb, err := googlecloudsql.NewInstancesService(client).Get(b.ProjectId, instance.Name).Do()
if err != nil {
return fmt.Errorf("Error getting instance from API: %s", err)
}
// update db information
instance.Url = clouddb.SelfLink
instance.Location = clouddb.Region
// update instance information
instanceInfo.Host = clouddb.IpAddresses[0].IpAddress
instanceInfo.Region = clouddb.Region
return instance.SetOtherDetails(instanceInfo)
}
// createDatabase creates tha database on the instance referenced by ServiceInstanceDetails.
func (b *CloudSQLBroker) createDatabase(ctx context.Context, instance *models.ServiceInstanceDetails) error {
var instanceInfo InstanceInformation
if err := json.Unmarshal([]byte(instance.OtherDetails), &instanceInfo); err != nil {
return fmt.Errorf("Error unmarshalling instance information.")
}
client, err := b.createClient(ctx)
if err != nil {
return err
}
d := googlecloudsql.Database{Name: instanceInfo.DatabaseName}
op, err := client.Databases.Insert(b.ProjectId, instance.Name, &d).Do()
if err != nil {
return fmt.Errorf("Error creating database: %s", err)
}
// poll for the database creation operation to be completed
// XXX: return this error exactly as is from the google api
return b.pollOperationUntilDone(ctx, op, b.ProjectId)
}
func (b *CloudSQLBroker) pollOperation(ctx context.Context, opterationId string) (bool, error) {
client, err := b.createClient(ctx)
if err != nil {
return false, err
}
// get the status of the operation
operation, err := googlecloudsql.NewOperationsService(client).Get(b.ProjectId, opterationId).Do()
if err != nil {
return false, err
}
if operation.Status == "DONE" {
if operation.Error == nil {
return true, nil
} else {
errs := ""
for _, err := range operation.Error.Errors {
errs += fmt.Sprintf("%s: %q; ", err.Code, err.Message)
}
return true, errors.New(errs)
}
}
return false, nil
}
// pollOperationUntilDone loops and waits until a cloudsql operation is done, returning an error if any is encountered
// XXX: note that for this function in particular, we are being explicit to return errors from the google api exactly
// as we get them, because further up the stack these errors will be evaluated differently and need to be preserved
func (b *CloudSQLBroker) pollOperationUntilDone(ctx context.Context, op *googlecloudsql.Operation, projectId string) error {
sqlService, err := b.createClient(ctx)
if err != nil {
return err
}
opsService := googlecloudsql.NewOperationsService(sqlService)
for {
status, err := opsService.Get(projectId, op.Name).Do()
if err != nil {
return err
}
if status.EndTime != "" {
return nil
}
b.Logger.Info("waiting for operation", lager.Data{"operation": op.Name, "status": status.Status})
// sleep for 1 second between polling so we don't hit our rate limit
time.Sleep(time.Second)
}
}
// Deprovision issues a delete call on the database instance.
func (b *CloudSQLBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
sqlService, err := b.createClient(ctx)
if err != nil {
return nil, err
}
return nil, b.deleteInstance(ctx, sqlService, instance.Name)
}
// deleteInstance deprovisions a single CloudSQL instance and its failover if
// it exists.
func (b *CloudSQLBroker) deleteInstance(ctx context.Context, sqlService *sqladmin.Service, instanceName string) error {
b.Logger.Info("deleting instance", lager.Data{"name": instanceName})
actualInstance, err := sqlService.Instances.Get(b.ProjectId, instanceName).Do()
if err != nil {
// the instance might have already been deleted
if isErrStatus(err, http.StatusNotFound) {
b.Logger.Info("instance did not exist, skipping deletion", lager.Data{"name": instanceName})
return nil
}
return fmt.Errorf("couldn't delete instance: %s", err)
}
if actualInstance.FailoverReplica != nil && actualInstance.FailoverReplica.Name != "" {
b.Logger.Info("instance has a failover, deleting that first", lager.Data{"name": instanceName, "failover": actualInstance.FailoverReplica.Name})
if err := b.deleteInstance(ctx, sqlService, actualInstance.FailoverReplica.Name); err != nil {
return fmt.Errorf("couldn't delete failover: %s", err)
}
}
return b.retryWhileConflict(ctx, "instance", instanceName, func() (*sqladmin.Operation, error) {
return sqlService.Instances.Delete(b.ProjectId, instanceName).Do()
})
}
func isErrStatus(err error, httpStatusCode int) bool {
if gerr, ok := err.(*googleapi.Error); ok {
return gerr.Code == httpStatusCode
}
return false
}
// ProvisionsAsync indicates that CloudSQL uses asynchronous provisioning.
func (b *CloudSQLBroker) ProvisionsAsync() bool {
return true
}
// DeprovisionsAsync indicates that CloudSQL uses asynchronous deprovisioning.
func (b *CloudSQLBroker) DeprovisionsAsync() bool {
return false
}
func (b *CloudSQLBroker) createClient(ctx context.Context) (*googlecloudsql.Service, error) {
client, err := googlecloudsql.New(b.HttpConfig.Client(ctx))
if err != nil {
return nil, fmt.Errorf("Couldn't instantiate CloudSQL API client: %s", err)
}
client.UserAgent = utils.CustomUserAgent
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/providers/builtin/cloudsql/mysql-definition.go | pkg/providers/builtin/cloudsql/mysql-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 cloudsql
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
const (
MySqlServiceId = "4bc59b9a-8520-409f-85da-1c7552315863"
CloudsqlMySQLName = "google-cloudsql-mysql"
)
// MysqlServiceDefinition creates a new ServiceDefinition object for the MySQL service.
func MysqlServiceDefinition() *broker.ServiceDefinition {
definition := buildDatabase(cloudSQLOptions{
DatabaseType: mySQLDatabaseType,
CustomizableActivationPolicy: true,
AdminControlsTier: true,
AdminControlsMaxDiskSize: true,
VPCNetwork: false,
})
definition.Id = MySqlServiceId
definition.Plans = []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "7d8f9ade-30c1-4c96-b622-ea0205cc5f0b",
Name: "mysql-db-f1-micro",
Description: "MySQL on a db-f1-micro (Shared CPUs, 0.6 GB/RAM, 3062 GB/disk, 250 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-f1-micro", "max_disk_size": "3062"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "b68bf4d8-1636-4121-af2f-087e46189929",
Name: "mysql-db-g1-small",
Description: "MySQL on a db-g1-small (Shared CPUs, 1.7 GB/RAM, 3062 GB/disk, 1,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-g1-small", "max_disk_size": "3062"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "bdfd8033-c2b9-46e9-9b37-1f3a5889eef4",
Name: "mysql-db-n1-standard-1",
Description: "MySQL on a db-n1-standard-1 (1 CPUs, 3.75 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-standard-1", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "2c99e938-4c1e-4da7-810a-94c9f5b71b57",
Name: "mysql-db-n1-standard-2",
Description: "MySQL on a db-n1-standard-2 (2 CPUs, 7.5 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-standard-2", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "d520a5f5-7485-4a83-849b-5439f911fe26",
Name: "mysql-db-n1-standard-4",
Description: "MySQL on a db-n1-standard-4 (4 CPUs, 15 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-standard-4", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "7ef42bb4-87e3-4ead-8118-4e88c98ed2e6",
Name: "mysql-db-n1-standard-8",
Description: "MySQL on a db-n1-standard-8 (8 CPUs, 30 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-standard-8", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "200bd90a-4323-46d8-8aa5-afd4601498d0",
Name: "mysql-db-n1-standard-16",
Description: "MySQL on a db-n1-standard-16 (16 CPUs, 60 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-standard-16", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "52305df2-1e64-4cdb-a4c9-bb5dddb33c3e",
Name: "mysql-db-n1-standard-32",
Description: "MySQL on a db-n1-standard-32 (32 CPUs, 120 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-standard-32", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "e45d7c44-4990-4dac-a14d-c5127e9ae0c5",
Name: "mysql-db-n1-standard-64",
Description: "MySQL on a db-n1-standard-64 (64 CPUs, 240 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-standard-64", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "07b8a04c-0efe-42d3-8b2c-2c23f7c79583",
Name: "mysql-db-n1-highmem-2",
Description: "MySQL on a db-n1-highmem-2 (2 CPUs, 13 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-highmem-2", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "50fa4baa-e36f-41c3-bbe9-c986d9fbe3c8",
Name: "mysql-db-n1-highmem-4",
Description: "MySQL on a db-n1-highmem-4 (4 CPUs, 26 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-highmem-4", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "6e8e5bc3-bf68-4e57-bda1-d9c9a67faee0",
Name: "mysql-db-n1-highmem-8",
Description: "MySQL on a db-n1-highmem-8 (8 CPUs, 52 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-highmem-8", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "3c83ff6b-165e-47bf-9bba-f4801390d0ff",
Name: "mysql-db-n1-highmem-16",
Description: "MySQL on a db-n1-highmem-16 (16 CPUs, 104 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-highmem-16", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "cbc6d376-8fd3-4a34-9ab5-324311f038f6",
Name: "mysql-db-n1-highmem-32",
Description: "MySQL on a db-n1-highmem-32 (32 CPUs, 208 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"max_disk_size": "10230", "tier": "db-n1-highmem-32"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "b0742cc5-caba-4b8d-98e0-03380ae9522b",
Name: "mysql-db-n1-highmem-64",
Description: "MySQL on a db-n1-highmem-64 (64 CPUs, 416 GB/RAM, 10230 GB/disk, 4,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-n1-highmem-64", "max_disk_size": "10230"},
},
}
definition.ProvisionComputedVariables = append(definition.ProvisionComputedVariables, varcontext.DefaultVariable{
Name: "_",
Default: `${assert(regexp.matches("^(d|D)[0-9]+$", tier) == false, "First generation support will end March 25th, 2020, please use a second gen machine type.")}`,
Overwrite: true,
})
definition.Examples = []broker.ServiceExample{
{
Name: "HA Instance",
Description: "A regionally available database with automatic failover.",
PlanId: "7d8f9ade-30c1-4c96-b622-ea0205cc5f0b",
ProvisionParams: map[string]interface{}{
"backups_enabled": "true",
"binlog": "true",
"availability_type": "REGIONAL",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
{
Name: "Development Sandbox",
Description: "An inexpensive MySQL sandbox for developing with no backups.",
PlanId: "7d8f9ade-30c1-4c96-b622-ea0205cc5f0b",
ProvisionParams: map[string]interface{}{
"backups_enabled": "false",
"binlog": "false",
"disk_size": "10",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
}
return definition
}
| 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/providers/builtin/cloudsql/postgres-definition.go | pkg/providers/builtin/cloudsql/postgres-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 cloudsql
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
)
const PostgresServiceId = "cbad6d78-a73c-432d-b8ff-b219a17a803a"
// PostgresServiceDefinition creates a new ServiceDefinition object for the PostgreSQL service.
func PostgresServiceDefinition() *broker.ServiceDefinition {
definition := buildDatabase(cloudSQLOptions{
DatabaseType: postgresDatabaseType,
CustomizableActivationPolicy: true,
AdminControlsTier: true,
AdminControlsMaxDiskSize: true,
VPCNetwork: false,
})
definition.Id = PostgresServiceId
definition.Name = "google-cloudsql-postgres"
definition.Plans = []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "2513d4d9-684b-4c3c-add4-6404969006de",
Name: "postgres-db-f1-micro",
Description: "PostgreSQL on a db-f1-micro (Shared CPUs, 0.6 GB/RAM, 3062 GB/disk, 250 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"max_disk_size": "3062", "tier": "db-f1-micro"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "6c1174d8-243c-44d1-b7a8-e94a779f67f5",
Name: "postgres-db-g1-small",
Description: "PostgreSQL on a db-g1-small (Shared CPUs, 1.7 GB/RAM, 3062 GB/disk, 1,000 Connections)",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-g1-small", "max_disk_size": "3062"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "c4e68ab5-34ca-4d02-857d-3e6b3ab079a7",
Name: "postgres-db-n1-standard-1",
Description: "PostgreSQL with 1 CPU, 3.75 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-1-3840", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "3f578ecf-885c-4b60-b38b-60272f34e00f",
Name: "postgres-db-n1-standard-2",
Description: "PostgreSQL with 2 CPUs, 7.5 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-2-7680", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "b7fcab5d-d66d-4e82-af16-565e84cef7f9",
Name: "postgres-db-n1-standard-4",
Description: "PostgreSQL with 4 CPUs, 15 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-4-15360", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "4b2fa14a-caf1-42e0-bd8c-3342502008a8",
Name: "postgres-db-n1-standard-8",
Description: "PostgreSQL with 8 CPUs, 30 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-8-30720", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "ca2e770f-bfa5-4fb7-a249-8b943c3474ca",
Name: "postgres-db-n1-standard-16",
Description: "PostgreSQL with 16 CPUs, 60 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-16-61440", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "b44f8294-b003-4a50-80c2-706858073f44",
Name: "postgres-db-n1-standard-32",
Description: "PostgreSQL with 32 CPUs, 120 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"max_disk_size": "10230", "tier": "db-custom-32-122880"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "d97326e0-5af2-4da5-b970-b4772d59cded",
Name: "postgres-db-n1-standard-64",
Description: "PostgreSQL with 64 CPUs, 240 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-64-245760", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "c10f8691-02f5-44eb-989f-7217393012ca",
Name: "postgres-db-n1-highmem-2",
Description: "PostgreSQL with 2 CPUs, 13 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-2-13312", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "610cc78d-d26a-41a9-90b7-547a44517f03",
Name: "postgres-db-n1-highmem-4",
Description: "PostgreSQL with 4 CPUs, 26 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-4-26624", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "2a351e8d-958d-4c4f-ae46-c984fec18740",
Name: "postgres-db-n1-highmem-8",
Description: "PostgreSQL with 8 CPUs, 52 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-8-53248", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "51d3ca0c-9d21-447d-a395-3e0dc0659775",
Name: "postgres-db-n1-highmem-16",
Description: "PostgreSQL with 16 CPUs, 104 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-16-106496", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "2e72b386-f7ce-4f0d-a149-9f9a851337d4",
Name: "postgres-db-n1-highmem-32",
Description: "PostgreSQL with 32 CPUs, 208 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-32-212992", "max_disk_size": "10230"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "82602649-e4ac-4a2f-b80d-dacd745aed6a",
Name: "postgres-db-n1-highmem-64",
Description: "PostgreSQL with 64 CPUs, 416 GB/RAM, 10230 GB/disk, supporting 4,000 connections.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"tier": "db-custom-64-425984", "max_disk_size": "10230"},
},
}
definition.Examples = []broker.ServiceExample{
{
Name: "Dedicated Machine Sandbox",
Description: "A low end PostgreSQL sandbox that uses a dedicated machine.",
PlanId: "c4e68ab5-34ca-4d02-857d-3e6b3ab079a7",
ProvisionParams: map[string]interface{}{
"backups_enabled": "false",
"disk_size": "25",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
{
Name: "Development Sandbox",
Description: "An inexpensive PostgreSQL sandbox for developing with no backups.",
PlanId: "2513d4d9-684b-4c3c-add4-6404969006de",
ProvisionParams: map[string]interface{}{
"backups_enabled": "false",
"disk_size": "10",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
{
Name: "HA Instance",
Description: "A regionally available database with automatic failover.",
PlanId: "c4e68ab5-34ca-4d02-857d-3e6b3ab079a7",
ProvisionParams: map[string]interface{}{
"backups_enabled": "false",
"disk_size": "25",
"availability_type": "REGIONAL",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
}
return definition
}
| 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/providers/builtin/cloudsql/mysql-vpc-definition.go | pkg/providers/builtin/cloudsql/mysql-vpc-definition.go | package cloudsql
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
)
const mySQLVPCID = "b48d2a6b-b1b0-499f-8389-57ba33bfbb19"
// MySQLVPCServiceDefinition creates a new ServiceDefinition object for the MySQL service
// on a VPC.
func MySQLVPCServiceDefinition() *broker.ServiceDefinition {
definition := buildDatabase(cloudSQLOptions{
DatabaseType: mySQLDatabaseType,
CustomizableActivationPolicy: false,
AdminControlsTier: false,
AdminControlsMaxDiskSize: false,
VPCNetwork: true,
})
definition.Id = mySQLVPCID
definition.Plans = []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "89e2c84e-4d5c-457c-ad14-329dcf44b806",
Name: "default",
Description: "MySQL attached to a VPC",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
}
definition.Examples = []broker.ServiceExample{
{
Name: "HA Instance",
Description: "A regionally available database with automatic failover.",
PlanId: "89e2c84e-4d5c-457c-ad14-329dcf44b806",
ProvisionParams: map[string]interface{}{
"tier": "db-n1-standard-1",
"backups_enabled": "true",
"binlog": "true",
"availability_type": "REGIONAL",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
{
Name: "Development Sandbox",
Description: "An inexpensive MySQL sandbox for developing with no backups.",
PlanId: "89e2c84e-4d5c-457c-ad14-329dcf44b806",
ProvisionParams: map[string]interface{}{
"tier": "db-n1-standard-1",
"backups_enabled": "false",
"binlog": "false",
"disk_size": "10",
},
BindParams: map[string]interface{}{
"role": "cloudsql.editor",
},
},
}
return definition
}
| 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/providers/builtin/cloudsql/builder.go | pkg/providers/builtin/cloudsql/builder.go | // Copyright 2020 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 cloudsql
import (
"fmt"
"strings"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"golang.org/x/oauth2/jwt"
)
type databaseType struct {
Name string
URIFormat string
CustomizableBinlog bool
DefaultVersion string
Versions map[interface{}]string
InstanceNameLength int
Tags []string
}
var mySQLDatabaseType = databaseType{
Name: "MySQL",
URIFormat: `${UriPrefix}mysql://${str.queryEscape(Username)}:${str.queryEscape(Password)}@${str.queryEscape(host)}/${str.queryEscape(database_name)}?ssl_mode=required`,
CustomizableBinlog: true,
DefaultVersion: mySqlSecondGenDefaultVersion,
Versions: map[interface{}]string{
"MYSQL_5_6": "MySQL 5.6.X",
"MYSQL_5_7": "MySQL 5.7.X",
},
InstanceNameLength: 84,
Tags: []string{"gcp", "cloudsql", "mysql"},
}
var postgresDatabaseType = databaseType{
Name: "PostgreSQL",
URIFormat: `${UriPrefix}postgres://${str.queryEscape(Username)}:${str.queryEscape(Password)}@${str.queryEscape(host)}/${str.queryEscape(database_name)}?sslmode=require&sslcert=${str.queryEscape(ClientCert)}&sslkey=${str.queryEscape(ClientKey)}&sslrootcert=${str.queryEscape(CaCert)}`,
CustomizableBinlog: false,
DefaultVersion: "POSTGRES_11",
Versions: map[interface{}]string{
"POSTGRES_9_6": "PostgreSQL 9.6.X",
"POSTGRES_10": "PostgreSQL 10",
"POSTGRES_11": "PostgreSQL 11",
"POSTGRES_12": "PostgreSQL 12",
},
InstanceNameLength: 86,
Tags: []string{"gcp", "cloudsql", "postgres"},
}
type cloudSQLOptions struct {
DatabaseType databaseType
CustomizableActivationPolicy bool
AdminControlsTier bool
AdminControlsMaxDiskSize bool
VPCNetwork bool
}
func buildDatabase(opts cloudSQLOptions) *broker.ServiceDefinition {
// Initial
name := strings.ToLower(fmt.Sprintf("google-cloudsql-%s", opts.DatabaseType.Name))
if opts.VPCNetwork {
name += "-vpc"
}
defn := &broker.ServiceDefinition{
Name: name,
Description: fmt.Sprintf("Google CloudSQL for %[1]s is a fully-managed %[1]s database service.", opts.DatabaseType.Name),
DisplayName: fmt.Sprintf("Google CloudSQL for %s", opts.DatabaseType.Name),
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/sql.svg",
DocumentationUrl: "https://cloud.google.com/sql/docs/",
SupportUrl: "https://cloud.google.com/sql/docs/getting-support/",
Tags: opts.DatabaseType.Tags,
Bindable: true,
PlanUpdateable: false,
DefaultRoleWhitelist: roleWhitelist(),
BindInputVariables: commonBindVariables(),
BindOutputVariables: commonBindOutputVariables(),
BindComputedVariables: commonBindComputedVariables(),
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &CloudSQLBroker{
BrokerBase: bb,
uriFormat: opts.DatabaseType.URIFormat,
}
},
IsBuiltin: true,
}
// Database type specific stuff
defn.ProvisionInputVariables = []broker.BrokerVariable{
{
FieldName: "instance_name",
Type: broker.JsonTypeString,
Details: "Name of the CloudSQL instance.",
Default: identifierTemplate,
Constraints: validation.NewConstraintBuilder().
Pattern("^[a-z][a-z0-9-]+$").
MaxLength(opts.DatabaseType.InstanceNameLength).
Build(),
},
{
FieldName: "database_name",
Type: broker.JsonTypeString,
Details: "Name of the database inside of the instance. Must be a valid identifier for your chosen database type.",
Default: identifierTemplate,
},
{
FieldName: "version",
Type: broker.JsonTypeString,
Details: "The database engine type and version.",
Default: opts.DatabaseType.DefaultVersion,
Enum: opts.DatabaseType.Versions,
},
}
defn.ProvisionComputedVariables = []varcontext.DefaultVariable{
{Name: "labels", Default: `${json.marshal(request.default_labels)}`, Overwrite: true},
// legacy behavior dictates that empty values get defaults
{Name: "instance_name", Default: `${instance_name == "" ? "` + identifierTemplate + `" : instance_name}`, Overwrite: true},
{Name: "database_name", Default: `${database_name == "" ? "` + identifierTemplate + `" : database_name}`, Overwrite: true},
}
if opts.CustomizableActivationPolicy {
defn.ProvisionInputVariables = append(defn.ProvisionInputVariables, broker.BrokerVariable{
FieldName: "activation_policy",
Type: broker.JsonTypeString,
Details: "The activation policy specifies when the instance is activated; it is applicable only when the instance state is RUNNABLE.",
Default: "ALWAYS",
Enum: map[interface{}]string{
"ALWAYS": "Always, instance is always on.",
"NEVER": "Never, instance does not turn on if a request arrives.",
},
})
} else {
defn.ProvisionComputedVariables = append(defn.ProvisionComputedVariables, varcontext.DefaultVariable{
Name: "activation_policy",
Default: `ALWAYS`,
Overwrite: true,
})
}
if opts.DatabaseType.CustomizableBinlog {
defn.ProvisionInputVariables = append(defn.ProvisionInputVariables, broker.BrokerVariable{
FieldName: "binlog",
Type: broker.JsonTypeString,
Details: "Whether binary log is enabled. Must be enabled for high availability.",
Default: "true",
Enum: map[interface{}]string{
"true": "use binary log",
"false": "do not use binary log",
},
})
} else {
defn.ProvisionComputedVariables = append(defn.ProvisionComputedVariables, varcontext.DefaultVariable{
Name: "binlog",
Default: `false`,
Overwrite: true,
})
}
if opts.AdminControlsTier {
defn.PlanVariables = append(defn.PlanVariables, broker.BrokerVariable{
FieldName: "tier",
Type: broker.JsonTypeString,
Details: "The machine type the database will run on. MySQL has predefined tiers, other databases use the a string of the form db-custom-[CPUS]-[MEMORY_MBS], where memory is at least 3840.",
Required: true,
})
} else {
defn.ProvisionInputVariables = append(defn.ProvisionInputVariables, broker.BrokerVariable{
FieldName: "tier",
Type: broker.JsonTypeString,
Details: "The machine type the database will run on. MySQL has predefined tiers, other databases use the a string of the form db-custom-[CPUS]-[MEMORY_MBS], where memory is at least 3840.",
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Examples("db-n1-standard-1", "db-custom-1-3840").
Build(),
})
}
if opts.AdminControlsMaxDiskSize {
defn.PlanVariables = append(defn.PlanVariables, broker.BrokerVariable{
FieldName: "max_disk_size",
Type: broker.JsonTypeString,
Details: "Maximum disk size in GB, 10 is the minimum.",
Default: "10",
Required: true,
})
defn.ProvisionComputedVariables = append(defn.ProvisionComputedVariables, varcontext.DefaultVariable{
Name: "_",
Default: `${assert(disk_size <= max_disk_size, "disk size (${disk_size}) is greater than max allowed disk size for this plan (${max_disk_size})")}`,
Overwrite: true,
})
} else {
// no-op, max_disk_size is an artificial constraint
}
if opts.VPCNetwork {
defn.ProvisionInputVariables = append(defn.ProvisionInputVariables, broker.BrokerVariable{
FieldName: "private_network",
Type: broker.JsonTypeString,
Details: "The private network to attach to. If specified the instance will only be accessible on the VPC.",
Default: "default",
Constraints: validation.NewConstraintBuilder().
Examples("projects/my-project/global/networks/default").
Build(),
})
defn.ProvisionComputedVariables = append(defn.ProvisionComputedVariables, varcontext.DefaultVariable{
Name: "authorized_networks",
Default: ``,
Overwrite: true,
})
} else {
defn.ProvisionInputVariables = append(
defn.ProvisionInputVariables,
broker.BrokerVariable{
FieldName: "authorized_networks",
Type: broker.JsonTypeString,
Details: "A comma separated list without spaces.",
Default: "",
},
)
defn.ProvisionComputedVariables = append(defn.ProvisionComputedVariables, varcontext.DefaultVariable{
Name: "private_network",
Default: ``,
Overwrite: true,
})
}
defn.ProvisionInputVariables = append(defn.ProvisionInputVariables, commonProvisionVariables()...)
return defn
}
| 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/providers/builtin/cloudsql/common-definition.go | pkg/providers/builtin/cloudsql/common-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 cloudsql
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
)
const (
passwordTemplate = "${rand.base64(32)}"
usernameTemplate = `sb${str.truncate(14, time.nano())}`
identifierTemplate = `sb-${counter.next()}-${time.nano()}`
)
func roleWhitelist() []string {
return []string{
"cloudsql.editor",
"cloudsql.viewer",
"cloudsql.client",
}
}
func commonBindVariables() []broker.BrokerVariable {
return append(accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist(), "cloudsql.client"),
broker.BrokerVariable{
FieldName: "jdbc_uri_format",
Type: broker.JsonTypeString,
Details: "If `true`, `uri` field will contain a JDBC formatted URI.",
Default: "false",
Enum: map[interface{}]string{
"true": "return a JDBC formatted URI",
"false": "return a SQL formatted URI",
},
},
broker.BrokerVariable{
FieldName: "username",
Type: broker.JsonTypeString,
Details: "The SQL username for the account.",
Default: `sb${str.truncate(14, time.nano())}`,
},
broker.BrokerVariable{
FieldName: "password",
Type: broker.JsonTypeString,
Details: "The SQL password for the account.",
Default: "${rand.base64(32)}",
},
)
}
func commonBindComputedVariables() []varcontext.DefaultVariable {
serviceAccountComputed := accountmanagers.ServiceAccountBindComputedVariables()
sqlComputed := []varcontext.DefaultVariable{
// legacy behavior dictates that empty values get defaults
{Name: "password", Default: `${password == "" ? "` + passwordTemplate + `" : password}`, Overwrite: true},
{Name: "username", Default: `${username == "" ? "` + usernameTemplate + `" : username}`, Overwrite: true},
// necessary additions
{Name: "certname", Default: `${str.truncate(10, request.binding_id)}cert`, Overwrite: true},
{Name: "db_name", Default: `${instance.name}`, Overwrite: true},
}
return append(serviceAccountComputed, sqlComputed...)
}
func commonProvisionVariables() []broker.BrokerVariable {
return []broker.BrokerVariable{
{
FieldName: "region",
Type: broker.JsonTypeString,
Details: "The geographical region. See the instance locations list https://cloud.google.com/sql/docs/mysql/instance-locations for which regions support which databases.",
Default: "us-central",
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Examples("northamerica-northeast1", "southamerica-east1", "us-east1").
Build(),
},
{
FieldName: "disk_size",
Type: broker.JsonTypeString,
Details: "In GB.",
Default: "10",
Constraints: validation.NewConstraintBuilder().
Pattern("^[1-9][0-9]+$").
MaxLength(5).
Examples("10", "500", "10230").
Build(),
},
{
FieldName: "database_flags",
Type: broker.JsonTypeString,
Details: "The database flags passed to the instance at startup (comma separated list of flags, e.g. general_log=on,skip_show_database=off).",
Default: "",
Constraints: validation.NewConstraintBuilder().
Pattern(`^(|([a-z_]+=[a-zA-Z0-9\.\+\:-]+)(,[a-z_]+=[a-zA-Z0-9\.\+\:-]+)*)$`).
Examples("long_query_time=10", "general_log=on,skip_show_database=off").
Build(),
},
{
FieldName: "zone",
Type: broker.JsonTypeString,
Details: "Optional, the specific zone in the region to run the instance.",
Default: "",
Constraints: validation.NewConstraintBuilder().
Pattern("^(|[A-Za-z][-a-z0-9A-Z]+)$").
Build(),
},
{
FieldName: "disk_type",
Type: broker.JsonTypeString,
Details: "The type of disk backing the database.",
Default: "PD_SSD",
Enum: map[interface{}]string{
"PD_SSD": "flash storage drive",
"PD_HDD": "magnetic hard drive",
},
},
{
FieldName: "maintenance_window_day",
Type: broker.JsonTypeString,
Details: "The day of week a CloudSQL instance should preferably be restarted for system maintenance purposes. (1-7), starting on Monday.",
Default: "1",
Enum: map[interface{}]string{
"1": "Monday",
"2": "Tuesday",
"3": "Wednesday",
"4": "Thursday",
"5": "Friday",
"6": "Saturday",
"7": "Sunday",
},
},
{
FieldName: "maintenance_window_hour",
Type: broker.JsonTypeString,
Details: "The hour of the day when disruptive updates (updates that require an instance restart) to this CloudSQL instance can be made. Hour of day 0-23.",
Default: "0",
Constraints: validation.NewConstraintBuilder().
Pattern("^([0-9]|1[0-9]|2[0-3])$").
Build(),
},
{
FieldName: "backups_enabled",
Type: broker.JsonTypeString,
Details: "Should daily backups be enabled for the service?",
Default: "true",
Enum: map[interface{}]string{
"true": "enable daily backups",
"false": "do not enable daily backups",
},
},
{
FieldName: "backup_start_time",
Type: broker.JsonTypeString,
Details: "Start time for the daily backup configuration in UTC timezone in the 24 hour format - HH:MM.",
Default: "06:00",
Constraints: validation.NewConstraintBuilder().
Pattern("^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$").
Build(),
},
{
FieldName: "replication_type",
Type: broker.JsonTypeString,
Details: "The type of replication this instance uses. This can be either ASYNCHRONOUS or SYNCHRONOUS.",
Default: "SYNCHRONOUS",
Enum: map[interface{}]string{
"ASYNCHRONOUS": "Asynchronous Replication",
"SYNCHRONOUS": "Synchronous Replication",
},
},
{
FieldName: "auto_resize",
Type: broker.JsonTypeString,
Details: "Configuration to increase storage size automatically.",
Default: "false",
Enum: map[interface{}]string{
"true": "increase storage size automatically",
"false": "do not increase storage size automatically",
},
},
{
FieldName: "auto_resize_limit",
Type: broker.JsonTypeString,
Details: "The maximum size to which storage capacity can be automatically increased.",
Default: "0",
Constraints: validation.NewConstraintBuilder().
Pattern("^[0-9][0-9]*$").
MaxLength(5).
Examples("10", "500", "10230").
Build(),
},
{
FieldName: "availability_type",
Type: broker.JsonTypeString,
Details: "Availability type specifies whether the instance serves data from multiple zones.",
Default: "ZONAL",
Enum: map[interface{}]string{
"ZONAL": "The instance serves data from only one zone (NOT highly available).",
"REGIONAL": "The instance serves data zones in a region (highly available).",
},
},
}
}
func commonBindOutputVariables() []broker.BrokerVariable {
return append(accountmanagers.ServiceAccountBindOutputVariables(), []broker.BrokerVariable{
// Certificate
{
FieldName: "CaCert",
Type: broker.JsonTypeString,
Details: "The server Certificate Authority's certificate.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("-----BEGIN CERTIFICATE-----BASE64 Certificate Text-----END CERTIFICATE-----").
Build(),
},
{
FieldName: "ClientCert",
Type: broker.JsonTypeString,
Details: "The client certificate.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("-----BEGIN CERTIFICATE-----BASE64 Certificate Text-----END CERTIFICATE-----").
Build(),
},
{
FieldName: "ClientKey",
Type: broker.JsonTypeString,
Details: "The client certificate key.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("-----BEGIN RSA PRIVATE KEY-----BASE64 Key Text-----END RSA PRIVATE KEY-----").
Build(),
},
{
FieldName: "Sha1Fingerprint",
Type: broker.JsonTypeString,
Details: "The SHA1 fingerprint of the client certificate.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("e6d0c68f35032c6c2132217d1f1fb06b12ed32e2").
Pattern(`^[0-9a-f]{40}$`).
Build(),
},
// Connection URI
{
FieldName: "UriPrefix",
Type: broker.JsonTypeString,
Details: "The connection prefix.",
Required: false,
Constraints: validation.NewConstraintBuilder().Examples("jdbc:", "").Build(),
},
{
FieldName: "Username",
Type: broker.JsonTypeString,
Details: "The name of the SQL user provisioned.",
Required: true,
Constraints: validation.NewConstraintBuilder().Examples("sb15404128767777").Build(),
},
{
FieldName: "Password",
Type: broker.JsonTypeString,
Details: "The database password for the SQL user.",
Required: true,
Constraints: validation.NewConstraintBuilder().Examples("N-JPz7h2RHPZ81jB5gDHdnluddnIFMWG4nd5rKjR_8A=").Build(),
},
{
FieldName: "database_name",
Type: broker.JsonTypeString,
Details: "The name of the database on the instance.",
Required: true,
Constraints: validation.NewConstraintBuilder().Examples("sb-2-1540412407295372465").Build(),
},
{
FieldName: "host",
Type: broker.JsonTypeString,
Details: "The hostname or IP address of the database instance.",
Required: true,
Constraints: validation.NewConstraintBuilder().Examples("127.0.0.1").Build(),
},
{
FieldName: "instance_name",
Type: broker.JsonTypeString,
Details: "The name of the database instance.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("sb-1-1540412407295273023").
Pattern("^[a-z][a-z0-9-]+$").
MaxLength(84).
Build(),
},
{
FieldName: "uri",
Type: broker.JsonTypeString,
Details: "A database connection string.",
Required: true,
Constraints: validation.NewConstraintBuilder().Examples("mysql://user:pass@127.0.0.1/sb-2-1540412407295372465?ssl_mode=required").Build(),
},
{
FieldName: "last_master_operation_id",
Type: broker.JsonTypeString,
Details: "(deprecated) The id of the last operation on the database.",
Required: false,
Constraints: validation.NewConstraintBuilder().Examples("mysql://user:pass@127.0.0.1/sb-2-1540412407295372465?ssl_mode=required").Build(),
},
{
FieldName: "region",
Type: broker.JsonTypeString,
Details: "The region the database is in.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Examples("northamerica-northeast1", "southamerica-east1", "us-east1").
Build(),
},
}...)
}
| 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/providers/builtin/cloudsql/sql_account_manager.go | pkg/providers/builtin/cloudsql/sql_account_manager.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 cloudsql
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
googlecloudsql "google.golang.org/api/sqladmin/v1beta4"
sqladmin "google.golang.org/api/sqladmin/v1beta4"
)
// inserts a new user into the database and creates new ssl certs
func (broker *CloudSQLBroker) createSqlCredentials(ctx context.Context, vars *varcontext.VarContext) (map[string]interface{}, error) {
userAccount, err := broker.createSqlUserAccount(ctx, vars)
if err != nil {
return nil, err
}
sslCert, err := broker.createSqlSslCert(ctx, vars)
if err != nil {
return nil, err
}
return varcontext.Builder().MergeStruct(userAccount).MergeStruct(sslCert).BuildMap()
}
type sqlUserAccount struct {
Username string `json:"Username"`
Password string `json:"Password"`
}
type sqlSslCert struct {
CaCert string `json:"CaCert"`
ClientCert string `json:"ClientCert"`
ClientKey string `json:"ClientKey"`
Sha1Fingerprint string `json:"Sha1Fingerprint"`
}
func (broker *CloudSQLBroker) createSqlUserAccount(ctx context.Context, vars *varcontext.VarContext) (*sqlUserAccount, error) {
request := &googlecloudsql.User{
Name: vars.GetString("username"),
Password: vars.GetString("password"),
}
instanceName := vars.GetString("db_name")
if err := vars.Error(); err != nil {
return nil, err
}
// create username, pw with grants
client, err := broker.createClient(ctx)
if err != nil {
return nil, err
}
op, err := client.Users.Insert(broker.ProjectId, instanceName, request).Do()
if err != nil {
return nil, fmt.Errorf("Error creating new database user: %s", err)
}
// poll for the user creation operation to be completed
if err := broker.pollOperationUntilDone(ctx, op, broker.ProjectId); err != nil {
return nil, fmt.Errorf("Error encountered waiting for operation %q to finish: %s", op.Name, err)
}
return &sqlUserAccount{
Username: request.Name,
Password: request.Password,
}, nil
}
func (broker *CloudSQLBroker) deleteSqlUserAccount(ctx context.Context, binding models.ServiceBindingCredentials, instance models.ServiceInstanceDetails) error {
var creds sqlUserAccount
if err := json.Unmarshal([]byte(binding.OtherDetails), &creds); err != nil {
return fmt.Errorf("Error unmarshalling credentials: %s", err)
}
client, err := broker.createClient(ctx)
if err != nil {
return err
}
userList, err := client.Users.List(broker.ProjectId, instance.Name).Do()
if err != nil {
return fmt.Errorf("Error fetching users to delete: %s", err)
}
// XXX: CloudSQL used to allow deleting users without specifying the host,
// however that no longer works. They also no longer accept a blank string
// which _is_ a valid host, so we expand to a single space string if the
// user we're trying to delete doesn't have some other host specified.
hostToDelete := ""
foundUser := false
for _, user := range userList.Items {
if user.Name == creds.Username {
hostToDelete = user.Host
foundUser = true
break
}
}
// XXX: If the user was already deleted, don't fail here because it could
// block deprovisioning.
if !foundUser {
return nil
}
if hostToDelete == "" {
hostToDelete = " "
}
return broker.retryWhileConflict(ctx, "user", creds.Username, func() (*sqladmin.Operation, error) {
return client.Users.Delete(broker.ProjectId, instance.Name, hostToDelete, creds.Username).Do()
})
}
func (broker *CloudSQLBroker) createSqlSslCert(ctx context.Context, vars *varcontext.VarContext) (*sqlSslCert, error) {
request := &googlecloudsql.SslCertsInsertRequest{
CommonName: vars.GetString("certname"),
}
instanceName := vars.GetString("db_name")
if err := vars.Error(); err != nil {
return nil, err
}
// create username, pw with grants
client, err := broker.createClient(ctx)
if err != nil {
return nil, err
}
newCert, err := client.SslCerts.Insert(broker.ProjectId, instanceName, request).Do()
if err != nil {
return nil, fmt.Errorf("Error creating SSL certs: %s", err)
}
// poll for the user creation operation to be completed
return &sqlSslCert{
Sha1Fingerprint: newCert.ClientCert.CertInfo.Sha1Fingerprint,
CaCert: newCert.ServerCaCert.Cert,
ClientCert: newCert.ClientCert.CertInfo.Cert,
ClientKey: newCert.ClientCert.CertPrivateKey,
}, nil
}
func (broker *CloudSQLBroker) deleteSqlSslCert(ctx context.Context, binding models.ServiceBindingCredentials, instance models.ServiceInstanceDetails) error {
var creds sqlSslCert
if err := json.Unmarshal([]byte(binding.OtherDetails), &creds); err != nil {
return fmt.Errorf("Error unmarshalling credentials: %s", err)
}
// If we didn't generate SSL certs for this binding, then we cannot delete them
if creds.CaCert == "" {
return nil
}
client, err := broker.createClient(ctx)
if err != nil {
return err
}
return broker.retryWhileConflict(ctx, "SSL Cert", creds.Sha1Fingerprint, func() (*sqladmin.Operation, error) {
return client.SslCerts.Delete(broker.ProjectId, instance.Name, creds.Sha1Fingerprint).Do()
})
}
func (broker *CloudSQLBroker) retryWhileConflict(ctx context.Context, typeName, instanceName string, callback func() (*sqladmin.Operation, error)) error {
for {
select {
case <-ctx.Done():
return fmt.Errorf("couldn't delete %s %q, timed out", typeName, instanceName)
default:
op, err := callback()
if err != nil {
if isErrStatus(err, http.StatusConflict) {
time.Sleep(5 * time.Second)
continue
}
return fmt.Errorf("couldn't delete %s: %s", typeName, err)
}
broker.Logger.Info("started deletion operation", lager.Data{"type": typeName, "name": instanceName, "op": op})
if err := broker.pollOperationUntilDone(ctx, op, broker.ProjectId); err != nil {
return fmt.Errorf("Error encountered waiting for operation %q to finish: %s", op.Name, 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/pkg/providers/builtin/cloudsql/broker_test.go | pkg/providers/builtin/cloudsql/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 cloudsql
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"github.com/spf13/cast"
"github.com/spf13/viper"
googlecloudsql "google.golang.org/api/sqladmin/v1beta4"
)
func TestCreateProvisionRequest(t *testing.T) {
viper.Set("service.google-cloudsql-mysql.plans", `[{
"tier": "db-n1-standard-1",
"max_disk_size": "512",
"id": "00000000-0000-0000-0000-000000000001",
"name": "second-gen",
"pricing_plan": "PACKAGE"
},{
"tier": "D16",
"max_disk_size": "512",
"id": "00000000-0000-0000-0000-000000000002",
"name": "first-gen",
"pricing_plan": "PACKAGE"
}]`)
viper.Set("service.google-cloudsql-postgres.plans", `[{
"tier": "db-n1-standard-1",
"max_disk_size": "512",
"id": "00000000-0000-0000-0000-000000000003",
"name": "second-gen",
"pricing_plan": "PACKAGE"
}]`)
defer viper.Reset()
mysqlSecondGenPlan := "00000000-0000-0000-0000-000000000001"
mysqlFirstgenPlan := "00000000-0000-0000-0000-000000000002"
postgresPlan := "c4e68ab5-34ca-4d02-857d-3e6b3ab079a7"
cases := map[string]struct {
Service *broker.ServiceDefinition
PlanId string
UserParams string
Validate func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation)
ErrContains string
}{
"blank instance names get generated": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{"instance_name":""}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if len(di.Name) == 0 {
t.Errorf("instance name wasn't generated")
}
},
},
"tiers matching (D|d)\\d+ get firstgen outputs for MySQL": {
Service: MysqlServiceDefinition(),
PlanId: mysqlFirstgenPlan,
UserParams: `{"name":""}`,
ErrContains: "First generation support will end March 25th, 2020, please use a second gen machine type",
},
"second-gen MySQL defaults": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if di.DatabaseVersion != mySqlSecondGenDefaultVersion {
t.Errorf("expected version to default to %s for first gen plan got %s", mySqlSecondGenDefaultVersion, di.DatabaseVersion)
}
if di.Settings.BackupConfiguration.BinaryLogEnabled == false {
t.Error("Expected binlog to be on by default for second-gen plans")
}
if len(di.Name) == 0 {
t.Error("instance name wasn't generated")
}
if di.Settings.MaintenanceWindow == nil {
t.Error("Expected maintenance window by default")
}
},
},
"PostgreSQL defaults": {
Service: PostgresServiceDefinition(),
PlanId: postgresPlan,
UserParams: `{}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if di.DatabaseVersion != postgresDefaultVersion {
t.Errorf("expected version to default to %s for first gen plan got %s", postgresDefaultVersion, di.DatabaseVersion)
}
if di.Settings.BackupConfiguration.BinaryLogEnabled == true {
t.Error("Expected binlog to be off for postgres")
}
if len(di.Name) == 0 {
t.Error("instance name wasn't generated")
}
if di.Settings.MaintenanceWindow == nil {
t.Error("Expected maintenance window by default")
}
},
},
"partial maintenance window day": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{"maintenance_window_day":"4"}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if di.Settings.MaintenanceWindow == nil {
t.Error("Expected maintenance window on partial fill")
}
if di.Settings.MaintenanceWindow.Day != 4 {
t.Errorf("Expected maintenance window day to be 4, got %v", di.Settings.MaintenanceWindow.Day)
}
},
},
"partial maintenance window hour": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{"maintenance_window_hour":"23"}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if di.Settings.MaintenanceWindow == nil {
t.Error("Expected maintenance window on partial fill")
}
if di.Settings.MaintenanceWindow.Hour != 23 {
t.Errorf("Expected maintenance window day to be 4, got %v", di.Settings.MaintenanceWindow.Hour)
}
},
},
"full maintenance window ": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{"maintenance_window_day":"4","maintenance_window_hour":"23"}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if di.Settings.MaintenanceWindow == nil {
t.Error("Expected maintenance window")
}
if di.Settings.MaintenanceWindow.Day != 4 {
t.Errorf("Expected maintenance window day to be 4, got %v", di.Settings.MaintenanceWindow.Day)
}
if di.Settings.MaintenanceWindow.Hour != 23 {
t.Errorf("Expected maintenance window day to be 4, got %v", di.Settings.MaintenanceWindow.Hour)
}
},
},
"instance info generates db on blank ": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{"database_name":""}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if len(ii.DatabaseName) == 0 {
t.Error("Expected DatabaseName to not be blank.")
}
},
},
"instance info has name and db name ": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{"database_name":"foo", "instance_name": "bar"}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {
if ii.DatabaseName != "foo" {
t.Errorf("Expected DatabaseName to be foo got %s.", ii.DatabaseName)
}
if ii.InstanceName != "bar" {
t.Errorf("Expected InstanceName to be bar got %s.", ii.InstanceName)
}
},
},
"mysql disk size greater than operator specified max fails": {
Service: MysqlServiceDefinition(),
PlanId: mysqlSecondGenPlan,
UserParams: `{"disk_size":"99999"}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {},
ErrContains: "disk size",
},
"postgres disk size greater than operator specified max fails": {
Service: PostgresServiceDefinition(),
PlanId: postgresPlan,
UserParams: `{"disk_size":"99999"}`,
Validate: func(t *testing.T, di googlecloudsql.DatabaseInstance, ii InstanceInformation) {},
ErrContains: "disk size",
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
details := brokerapi.ProvisionDetails{RawParameters: json.RawMessage(tc.UserParams), ServiceID: tc.Service.Id}
plan, err := tc.Service.GetPlanById(tc.PlanId)
if err != nil {
t.Fatalf("got error trying to find plan %s %v", tc.PlanId, err)
}
if plan == nil {
t.Fatalf("Expected plan with id %s to not be nil", tc.PlanId)
}
vars, err := tc.Service.ProvisionVariables("instance-id-here", details, *plan)
if err != nil {
if tc.ErrContains != "" && strings.Contains(err.Error(), tc.ErrContains) {
return
}
t.Fatalf("got error trying to get provision details %s %v", tc.PlanId, err)
}
request, instanceInfo, err := createProvisionRequest(vars)
if err != nil {
t.Fatalf("got unexpected error while creating provision request: %v", err)
}
if tc.ErrContains != "" {
t.Fatalf("Expected error containing %q, but got none.", tc.ErrContains)
}
tc.Validate(t, *request, *instanceInfo)
})
}
}
func TestPostgresCustomMachineTypes(t *testing.T) {
for _, plan := range PostgresServiceDefinition().Plans {
t.Run(plan.Name, func(t *testing.T) {
props := plan.ServiceProperties
tier := props["tier"]
if !strings.HasPrefix(tier, "db-custom") {
return
}
splitTier := strings.Split(tier, "-")
if len(splitTier) != 4 {
t.Errorf("Expected custom machine type to be in format db-custom-[NCPU]-[MEM_MB]")
}
cpu := cast.ToInt(splitTier[2])
mem := cast.ToInt(splitTier[3])
// Rules for custom machines
// https://cloud.google.com/compute/docs/instances/creating-instance-with-custom-machine-type#create
if cpu != 1 && cpu%2 != 0 {
t.Errorf("Only machine types with 1 vCPU or an even number of vCPUs can be created got %d", cpu)
}
memPerCpu := float64(mem) / float64(cpu)
if memPerCpu < (.9*1024) || memPerCpu > (6.5*1024) {
t.Errorf("Memory must be between 0.9 GB per vCPU, up to 6.5 GB per vCPU got %f MB/CPU", memPerCpu)
}
if mem%256 != 0 {
t.Errorf("The total memory of the instance must be a multiple of 256 MB, got: %d MB", mem)
}
if cpu > 64 {
t.Errorf("The maximum number of CPUs allowed are 64, got %d", cpu)
}
})
}
}
func TestBuildInstanceCredentials(t *testing.T) {
pgProvider := PostgresServiceDefinition().ProviderBuilder("project-id", nil, nil)
mysqlProvider := MysqlServiceDefinition().ProviderBuilder("project-id", nil, nil)
cases := map[string]struct {
serviceID string
bindDetails string
instanceDetails string
provider broker.ServiceProvider
expectedCreds map[string]interface{}
}{
"no prefix mysql": {
serviceID: MySqlServiceId,
instanceDetails: `{
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12"
}`,
bindDetails: `{
"Username": "sb15433468744175",
"Password": "pass=",
"UriPrefix": ""
}`,
provider: mysqlProvider,
expectedCreds: map[string]interface{}{
"Password": "pass=",
"UriPrefix": "",
"Username": "sb15433468744175",
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12",
"uri": "mysql://sb15433468744175:pass%3D@35.202.18.12/sb-2-1543346570614873901?ssl_mode=required",
},
},
"no prefix postgres": {
serviceID: PostgresServiceId,
instanceDetails: `{
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12"
}`,
bindDetails: `{
"ClientCert": "@clientcert",
"ClientKey": "@clientkey",
"CaCert": "@cacert",
"Username": "sb15433468744175",
"Password": "pass=",
"UriPrefix": ""
}`,
provider: pgProvider,
expectedCreds: map[string]interface{}{
"ClientCert": "@clientcert",
"ClientKey": "@clientkey",
"CaCert": "@cacert",
"Password": "pass=",
"UriPrefix": "",
"Username": "sb15433468744175",
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12",
"uri": "postgres://sb15433468744175:pass%3D@35.202.18.12/sb-2-1543346570614873901?sslmode=require&sslcert=%40clientcert&sslkey=%40clientkey&sslrootcert=%40cacert",
},
},
"prefix mysql": {
serviceID: MySqlServiceId,
instanceDetails: `{
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12"
}`,
bindDetails: `{
"Username": "sb15433468744175",
"Password": "pass=",
"UriPrefix": "jdbc:"
}`,
provider: mysqlProvider,
expectedCreds: map[string]interface{}{
"Password": "pass=",
"UriPrefix": "jdbc:",
"Username": "sb15433468744175",
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12",
"uri": "jdbc:mysql://sb15433468744175:pass%3D@35.202.18.12/sb-2-1543346570614873901?ssl_mode=required",
},
},
"prefix postgres": {
serviceID: PostgresServiceId,
instanceDetails: `{
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12"
}`,
bindDetails: `{
"ClientCert": "@clientcert",
"ClientKey": "@clientkey",
"CaCert": "@cacert",
"Username": "sb15433468744175",
"Password": "pass=",
"UriPrefix": "jdbc:"
}`,
provider: pgProvider,
expectedCreds: map[string]interface{}{
"ClientCert": "@clientcert",
"ClientKey": "@clientkey",
"CaCert": "@cacert",
"Password": "pass=",
"UriPrefix": "jdbc:",
"Username": "sb15433468744175",
"database_name": "sb-2-1543346570614873901",
"host": "35.202.18.12",
"uri": "jdbc:postgres://sb15433468744175:pass%3D@35.202.18.12/sb-2-1543346570614873901?sslmode=require&sslcert=%40clientcert&sslkey=%40clientkey&sslrootcert=%40cacert",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
bindRecord := models.ServiceBindingCredentials{
OtherDetails: tc.bindDetails,
}
instanceRecord := models.ServiceInstanceDetails{
ServiceId: tc.serviceID,
OtherDetails: tc.instanceDetails,
}
binding, err := tc.provider.BuildInstanceCredentials(context.Background(), bindRecord, instanceRecord)
if err != nil {
t.Error("expected no error, got:", err)
return
}
if !reflect.DeepEqual(binding.Credentials, tc.expectedCreds) {
t.Errorf("Expected credentials %#v, got %#v", tc.expectedCreds, binding.Credentials)
}
})
}
}
func Test_createProvisionRequest(t *testing.T) {
services := []*broker.ServiceDefinition{
MysqlServiceDefinition(),
PostgresServiceDefinition(),
MySQLVPCServiceDefinition(),
PostgresVPCServiceDefinition(),
}
for _, service := range services {
t.Run(service.Name, func(t *testing.T) {
for _, example := range service.Examples {
t.Run(example.Name, func(t *testing.T) {
vars := deterministicProvisionVariables(t, service, example)
req, _, err := createProvisionRequest(vars)
if err != nil {
t.Fatalf("couldn't createProvisionRequest: %v", err)
}
assertGolden(t, req, map[string]interface{}{
"example": example,
})
})
}
})
}
}
func assertGolden(t *testing.T, object interface{}, context map[string]interface{}) {
t.Helper()
contextText, err := json.MarshalIndent(context, "// ", "\t")
if err != nil {
t.Errorf("creating golden context: %v", err)
}
objectText, err := json.MarshalIndent(object, "", "\t")
if err != nil {
t.Errorf("creating golden object: %v", err)
}
goldenContents := fmt.Sprintf("// %s\n%s", string(contextText), string(objectText))
testPath := filepath.FromSlash(t.Name())
goldenPrefix := append([]string{"testdata", "golden"}, filepath.SplitList(testPath)...)
goldenPath := filepath.Join(goldenPrefix...)
if os.Getenv("UPDATE_GOLDEN") == "true" {
if err := os.MkdirAll(filepath.Dir(goldenPath), 0700); err != nil {
t.Fatalf("creating parent directory: %v", err)
}
if err := ioutil.WriteFile(goldenPath, []byte(goldenContents), 0600); err != nil {
t.Fatalf("creating golden file: %v", err)
}
t.Fatal("golden file updated, run without UPDATE_GOLDEN=true to test")
} else {
wantContents, err := ioutil.ReadFile(goldenPath)
if err != nil {
t.Fatalf("couldn't read golden file, run with UPDATE_GOLDEN=true to update: %v", err)
}
if string(wantContents) != string(goldenContents) {
t.Errorf("actual differed from golden actual: %s golden: %s", string(wantContents), string(goldenContents))
}
}
}
func deterministicProvisionVariables(t *testing.T, service *broker.ServiceDefinition, example broker.ServiceExample) *varcontext.VarContext {
t.Helper()
bytes, err := json.Marshal(example.ProvisionParams)
if err != nil {
t.Fatalf("couldn't marshal ProvisionParams for example: %v", err)
}
details := brokerapi.ProvisionDetails{
RawParameters: bytes,
ServiceID: service.Id,
}
plan, err := service.GetPlanById(example.PlanId)
if err != nil {
t.Fatalf("got error trying to find plan %s %v", example.PlanId, err)
}
vars1, err := service.ProvisionVariables("instance-id-here", details, *plan)
if err != nil {
t.Fatalf("couldn't create ProvisionVariables1: %v", err)
}
vars2, err := service.ProvisionVariables("instance-id-here", details, *plan)
if err != nil {
t.Fatalf("couldn't create ProvisionVariables2: %v", err)
}
vm1 := vars1.ToMap()
vm2 := vars2.ToMap()
merged := make(map[string]interface{})
for k := range vm1 {
if reflect.DeepEqual(vm1[k], vm2[k]) {
merged[k] = vm1[k]
} else {
// TODO: add additional types if necessary
merged[k] = "NONDETERMINISTIC"
}
}
context, err := varcontext.Builder().MergeMap(merged).Build()
if err != nil {
t.Fatalf("creating varcontext: %v", err)
}
return context
}
| 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/providers/builtin/datastore/broker.go | pkg/providers/builtin/datastore/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 datastore
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
// InstanceInformation holds the details needed to bind a service to a DatastoreBroker.
type InstanceInformation struct {
Namespace string `json:"namespace,omitempty"`
}
// DatastoreBroker is the service-broker back-end for creating and binding Datastore instances.
type DatastoreBroker struct {
base.BrokerBase
}
// Provision stores the namespace for future reference.
func (b *DatastoreBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
// return models.ServiceInstanceDetails{}, nil
ii := InstanceInformation{
Namespace: provisionContext.GetString("namespace"),
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
details := models.ServiceInstanceDetails{}
if err := details.SetOtherDetails(ii); err != nil {
return models.ServiceInstanceDetails{}, err
}
return details, nil
}
// Deprovision is a no-op call because only service accounts need to be bound/unbound for Datastore.
func (b *DatastoreBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
return nil, 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/providers/builtin/datastore/definition.go | pkg/providers/builtin/datastore/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 datastore
import (
"code.cloudfoundry.org/lager"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Datastore service.
func ServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "76d4abb2-fee7-4c8f-aee1-bcea2837f02b",
Name: "google-datastore",
Description: "Google Cloud Datastore is a NoSQL document database service.",
DisplayName: "Google Cloud Datastore",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/datastore.svg",
DocumentationUrl: "https://cloud.google.com/datastore/docs/",
SupportUrl: "https://cloud.google.com/datastore/docs/getting-support",
Tags: []string{"gcp", "datastore"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "05f1fb6b-b5f0-48a2-9c2b-a5f236507a97",
Name: "default",
Description: "Datastore default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
{
FieldName: "namespace",
Type: broker.JsonTypeString,
Details: "A context for the identifiers in your entity’s dataset. This ensures that different systems can all interpret an entity's data the same way, based on the rules for the entity’s particular namespace. Blank means the default namespace will be used.",
Default: "",
Constraints: validation.NewConstraintBuilder().
MaxLength(100).
Pattern("^[A-Za-z0-9_-]*$").
Build(),
},
},
BindInputVariables: []broker.BrokerVariable{},
BindComputedVariables: accountmanagers.FixedRoleBindComputedVariables("datastore.user"),
BindOutputVariables: append(accountmanagers.ServiceAccountBindOutputVariables(),
broker.BrokerVariable{
FieldName: "namespace",
Type: broker.JsonTypeString,
Details: "A context for the identifiers in your entity’s dataset.",
Required: false,
Constraints: validation.NewConstraintBuilder().
MaxLength(100).
Pattern("^[A-Za-z0-9_-]*$").
Build(),
},
),
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Creates a datastore and a user with the permission `datastore.user`.",
PlanId: "05f1fb6b-b5f0-48a2-9c2b-a5f236507a97",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
{
Name: "Custom Namespace",
Description: "Creates a datastore and returns the provided namespace along with bind calls.",
PlanId: "05f1fb6b-b5f0-48a2-9c2b-a5f236507a97",
ProvisionParams: map[string]interface{}{"namespace": "my-namespace"},
BindParams: map[string]interface{}{},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &DatastoreBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/stackdriver/debugger_definition.go | pkg/providers/builtin/stackdriver/debugger_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 stackdriver
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/pivotal-cf/brokerapi"
)
// StackdriverDebuggerServiceDefinition creates a new ServiceDefinition object
// for the Stackdriver Debugger service.
func StackdriverDebuggerServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "83837945-1547-41e0-b661-ea31d76eed11",
Name: "google-stackdriver-debugger",
Description: "Inspect the state of an app, at any code location, without stopping or slowing it down.",
DisplayName: "Stackdriver Debugger",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/debugger.svg",
DocumentationUrl: "https://cloud.google.com/debugger/docs/",
SupportUrl: "https://cloud.google.com/stackdriver/docs/getting-support",
Tags: []string{"gcp", "stackdriver", "debugger"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "10866183-a775-49e8-96e3-4e7a901e4a79",
Name: "default",
Description: "Stackdriver Debugger default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
BindInputVariables: []broker.BrokerVariable{},
BindComputedVariables: accountmanagers.FixedRoleBindComputedVariables("clouddebugger.agent"),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
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{}{},
},
},
ProviderBuilder: NewStackdriverAccountProvider,
IsBuiltin: 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/providers/builtin/stackdriver/broker.go | pkg/providers/builtin/stackdriver/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 stackdriver
import (
"context"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// StackdriverServiceAccountProvider is the provider for binding new services to Stackdriver.
// It has no-op calls for Provision and Deprovision because Stackdriver is a single-instance API service.
type StackdriverAccountProvider struct {
base.BrokerBase
}
// Provision is a no-op call because only service accounts need to be bound/unbound for Stackdriver.
func (b *StackdriverAccountProvider) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
return models.ServiceInstanceDetails{}, nil
}
// Deprovision is a no-op call because only service accounts need to be bound/unbound for Stackdriver.
func (b *StackdriverAccountProvider) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
return nil, nil
}
// NewStackdriverAccountProvider creates a new StackdriverAccountProvider for the given project.
func NewStackdriverAccountProvider(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &StackdriverAccountProvider{BrokerBase: bb}
}
| 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/providers/builtin/stackdriver/profiler_definition.go | pkg/providers/builtin/stackdriver/profiler_definition.go | // Copyright 2018 Google Inc.
//
// 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 stackdriver
import (
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
)
// StackdriverProfilerServiceDefinition creates a new ServiceDefinition object
// for the Stackdriver Profiler service.
func StackdriverProfilerServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "00b9ca4a-7cd6-406a-a5b7-2f43f41ade75",
Name: "google-stackdriver-profiler",
Description: "Continuous CPU and heap profiling to improve performance and reduce costs.",
DisplayName: "Stackdriver Profiler",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/stackdriver.svg",
DocumentationUrl: "https://cloud.google.com/profiler/docs/",
SupportUrl: "https://cloud.google.com/stackdriver/docs/getting-support",
Tags: []string{"gcp", "stackdriver", "profiler"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "594627f6-35f5-462f-9074-10fb033fb18a",
Name: "default",
Description: "Stackdriver Profiler default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
BindInputVariables: []broker.BrokerVariable{},
BindComputedVariables: accountmanagers.FixedRoleBindComputedVariables("cloudprofiler.agent"),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Creates an account with the permission `cloudprofiler.agent`.",
PlanId: "594627f6-35f5-462f-9074-10fb033fb18a",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
},
ProviderBuilder: NewStackdriverAccountProvider,
IsBuiltin: 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/providers/builtin/stackdriver/monitoring_definition.go | pkg/providers/builtin/stackdriver/monitoring_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 stackdriver
import (
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
)
// StackdriverMonitoringServiceDefinition creates a new ServiceDefinition object
// for the Stackdriver Monitoring service.
func StackdriverMonitoringServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "2bc0d9ed-3f68-4056-b842-4a85cfbc727f",
Name: "google-stackdriver-monitoring",
Description: "Stackdriver Monitoring provides visibility into the performance, uptime, and overall health of cloud-powered applications.",
DisplayName: "Stackdriver Monitoring",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/stackdriver.svg",
DocumentationUrl: "https://cloud.google.com/monitoring/docs/",
SupportUrl: "https://cloud.google.com/stackdriver/docs/getting-support",
Tags: []string{"gcp", "stackdriver", "monitoring", "preview"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "2e4b85c1-0ce6-46e4-91f5-eebeb373e3f5",
Name: "default",
Description: "Stackdriver Monitoring default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
BindInputVariables: []broker.BrokerVariable{},
BindComputedVariables: accountmanagers.FixedRoleBindComputedVariables("monitoring.metricWriter"),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Creates an account with the permission `monitoring.metricWriter` for writing metrics.",
PlanId: "2e4b85c1-0ce6-46e4-91f5-eebeb373e3f5",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
},
ProviderBuilder: NewStackdriverAccountProvider,
IsBuiltin: 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/providers/builtin/stackdriver/trace_definition.go | pkg/providers/builtin/stackdriver/trace_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 stackdriver
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/pivotal-cf/brokerapi"
)
// StackdriverTraceServiceDefinition creates a new ServiceDefinition object
// for the Stackdriver Trace service.
func StackdriverTraceServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "c5ddfe15-24d9-47f8-8ffe-f6b7daa9cf4a",
Name: "google-stackdriver-trace",
Description: "A real-time distributed tracing system.",
DisplayName: "Stackdriver Trace",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/trace.svg",
DocumentationUrl: "https://cloud.google.com/trace/docs/",
SupportUrl: "https://cloud.google.com/stackdriver/docs/getting-support",
Tags: []string{"gcp", "stackdriver", "trace"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "ab6c2287-b4bc-4ff4-a36a-0575e7910164",
Name: "default",
Description: "Stackdriver Trace default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
BindInputVariables: []broker.BrokerVariable{},
BindComputedVariables: accountmanagers.FixedRoleBindComputedVariables("cloudtrace.agent"),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
Examples: []broker.ServiceExample{
{
Name: "Basic Configuration",
Description: "Creates an account with the permission `cloudtrace.agent`.",
PlanId: "ab6c2287-b4bc-4ff4-a36a-0575e7910164",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
},
ProviderBuilder: NewStackdriverAccountProvider,
IsBuiltin: 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/providers/builtin/bigtable/broker.go | pkg/providers/builtin/bigtable/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 bigtable
import (
"errors"
"fmt"
googlebigtable "cloud.google.com/go/bigtable"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/net/context"
"google.golang.org/api/option"
)
// BigTableBroker is the service-broker back-end for creating and binding BigTable instances.
type BigTableBroker struct {
base.BrokerBase
}
// InstanceInformation holds the details needed to bind a service account to a
// BigTable instance after it has been provisioned.
type InstanceInformation struct {
InstanceId string `json:"instance_id"`
}
// storageTypes holds the valid value mapping for string storage types to their
// REST call equivalent.
var storageTypes = map[string]googlebigtable.StorageType{
"SSD": googlebigtable.SSD,
"HDD": googlebigtable.HDD,
}
// Provision creates a new Bigtable instance from the settings in the user-provided details and service plan.
func (b *BigTableBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
instanceName := provisionContext.GetString("name")
ic := googlebigtable.InstanceConf{
InstanceId: instanceName,
ClusterId: provisionContext.GetString("cluster_id"),
NumNodes: int32(provisionContext.GetInt("num_nodes")),
StorageType: storageTypes[provisionContext.GetString("storage_type")],
Zone: provisionContext.GetString("zone"),
DisplayName: provisionContext.GetString("display_name"),
}
if err := provisionContext.Error(); err != nil {
return models.ServiceInstanceDetails{}, err
}
// custom constraints
if instanceName == "" {
return models.ServiceInstanceDetails{}, errors.New("name must not be empty")
}
service, err := b.createClient(ctx)
if err != nil {
return models.ServiceInstanceDetails{}, err
}
if err := service.CreateInstance(ctx, &ic); err != nil {
return models.ServiceInstanceDetails{}, fmt.Errorf("Error creating new Bigtable instance: %s", err)
}
ii := InstanceInformation{
InstanceId: instanceName,
}
id := models.ServiceInstanceDetails{
Name: instanceName,
}
if err := id.SetOtherDetails(ii); err != nil {
return models.ServiceInstanceDetails{}, err
}
return id, nil
}
// Deprovision deletes the BigTable associated with the given instance.
func (b *BigTableBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
service, err := b.createClient(ctx)
if err != nil {
return nil, err
}
if err := service.DeleteInstance(ctx, instance.Name); err != nil {
return nil, fmt.Errorf("Error deleting Bigtable instance: %s", err)
}
return nil, nil
}
func (b *BigTableBroker) createClient(ctx context.Context) (*googlebigtable.InstanceAdminClient, error) {
co := option.WithUserAgent(utils.CustomUserAgent)
ct := option.WithTokenSource(b.HttpConfig.TokenSource(ctx))
client, err := googlebigtable.NewInstanceAdminClient(ctx, b.ProjectId, ct, co)
if err != nil {
return nil, fmt.Errorf("Couldn't instantiate Bigtable API client: %s", 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/providers/builtin/bigtable/broker_test.go | pkg/providers/builtin/bigtable/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 bigtable
import (
"encoding/json"
"reflect"
"testing"
"github.com/pivotal-cf/brokerapi"
)
func TestBigTableBroker_ProvisionVariables(t *testing.T) {
service := ServiceDefinition()
hddPlan := "65a49268-2c73-481e-80f3-9fde5bd5a654"
ssdPlan := "38aa0e65-624b-4998-9c06-f9194b56d252"
cases := map[string]struct {
UserParams string
PlanId string
ExpectedContext map[string]interface{}
}{
"hdd": {
UserParams: `{"name":"my-bt-instance"}`,
PlanId: hddPlan,
ExpectedContext: map[string]interface{}{
"num_nodes": "3",
"name": "my-bt-instance",
"cluster_id": "my-bt-instance-cluster",
"display_name": "my-bt-instance",
"zone": "us-east1-b",
"storage_type": "HDD",
},
},
"ssd": {
UserParams: `{"name":"my-bt-instance"}`,
PlanId: ssdPlan,
ExpectedContext: map[string]interface{}{
"num_nodes": "3",
"name": "my-bt-instance",
"cluster_id": "my-bt-instance-cluster",
"display_name": "my-bt-instance",
"zone": "us-east1-b",
"storage_type": "SSD",
},
},
"cluster truncates": {
UserParams: `{"name":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`,
PlanId: ssdPlan,
ExpectedContext: map[string]interface{}{
"num_nodes": "3",
"name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"cluster_id": "aaaaaaaaaaaaaaaaaaaa-cluster",
"display_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"zone": "us-east1-b",
"storage_type": "SSD",
},
},
"no defaults": {
UserParams: `{"name":"test-no-defaults", "cluster_id": "testcluster", "display_name":"test display"}`,
PlanId: ssdPlan,
ExpectedContext: map[string]interface{}{
"num_nodes": "3",
"name": "test-no-defaults",
"cluster_id": "testcluster",
"display_name": "test display",
"zone": "us-east1-b",
"storage_type": "SSD",
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
details := brokerapi.ProvisionDetails{RawParameters: json.RawMessage(tc.UserParams)}
plan, err := service.GetPlanById(tc.PlanId)
if err != nil {
t.Errorf("got error trying to find plan %s %v", tc.PlanId, err)
}
vars, err := service.ProvisionVariables("instance-id-here", details, *plan)
if err != nil {
t.Fatalf("got error while creating provision variables: %v", err)
}
if !reflect.DeepEqual(vars.ToMap(), tc.ExpectedContext) {
t.Errorf("Expected context: %#v got %#v", tc.ExpectedContext, vars.ToMap())
}
})
}
}
| 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/providers/builtin/bigtable/definition.go | pkg/providers/builtin/bigtable/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 bigtable
import (
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Bigtable service.
func ServiceDefinition() *broker.ServiceDefinition {
roleWhitelist := []string{
"bigtable.user",
"bigtable.reader",
"bigtable.viewer",
}
return &broker.ServiceDefinition{
Id: "b8e19880-ac58-42ef-b033-f7cd9c94d1fe",
Name: "google-bigtable",
Description: "A high performance NoSQL database service for large analytical and operational workloads.",
DisplayName: "Google Bigtable",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/bigtable.svg",
DocumentationUrl: "https://cloud.google.com/bigtable/",
SupportUrl: "https://cloud.google.com/bigtable/docs/support/getting-support",
Tags: []string{"gcp", "bigtable"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "65a49268-2c73-481e-80f3-9fde5bd5a654",
Name: "three-node-production-hdd",
Description: "BigTable HDD basic production plan: Approx: Reads: 1,500 QPS @ 200ms or Writes: 30,000 QPS @ 50ms or Scans: 540 MB/s, 24TB storage.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_type": "HDD", "num_nodes": "3"},
},
{
ServicePlan: brokerapi.ServicePlan{
ID: "38aa0e65-624b-4998-9c06-f9194b56d252",
Name: "three-node-production-ssd",
Description: "BigTable SSD basic production plan: Approx: Reads: 30,000 QPS @ 6ms or Writes: 30,000 QPS @ 6ms or Scans: 660 MB/s, 7.5TB storage.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{"storage_type": "SSD", "num_nodes": "3"},
},
},
ProvisionInputVariables: []broker.BrokerVariable{
{
FieldName: "name",
Type: broker.JsonTypeString,
Details: "The name of the Cloud Bigtable instance.",
Default: "pcf-sb-${counter.next()}-${time.nano()}",
Constraints: validation.NewConstraintBuilder().
MinLength(6).
MaxLength(33).
Pattern("^[a-z][-0-9a-z]+$").
Build(),
},
{
FieldName: "cluster_id",
Type: broker.JsonTypeString,
Details: "The ID of the Cloud Bigtable cluster.",
Default: "${str.truncate(20, name)}-cluster",
Constraints: validation.NewConstraintBuilder().
MinLength(6).
MaxLength(30).
Pattern("^[a-z][-0-9a-z]+[a-z]$").
Build(),
},
{
FieldName: "display_name",
Type: broker.JsonTypeString,
Details: "The human-readable display name of the Bigtable instance.",
Default: "${name}",
Constraints: validation.NewConstraintBuilder().
MinLength(4).
MaxLength(30).
Build(),
},
{
FieldName: "zone",
Type: broker.JsonTypeString,
Details: "The zone to create the Cloud Bigtable cluster in. Zones that support Bigtable instances are noted on the Cloud Bigtable locations page: https://cloud.google.com/bigtable/docs/locations.",
Default: "us-east1-b",
Constraints: validation.NewConstraintBuilder().
Pattern("^[A-Za-z][-a-z0-9A-Z]+$").
Examples("us-central1-a", "europe-west2-b", "asia-northeast1-a", "australia-southeast1-c").
Build(),
},
},
DefaultRoleWhitelist: roleWhitelist,
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault(roleWhitelist, "bigtable.user"),
BindOutputVariables: append(accountmanagers.ServiceAccountBindOutputVariables(),
broker.BrokerVariable{
FieldName: "instance_id",
Type: broker.JsonTypeString,
Details: "The name of the BigTable dataset.",
Required: true,
Constraints: validation.NewConstraintBuilder().
MinLength(6).
MaxLength(33).
Pattern("^[a-z][-0-9a-z]+$").
Build(),
},
),
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
PlanVariables: []broker.BrokerVariable{
{
FieldName: "storage_type",
Type: broker.JsonTypeString,
Details: "Either HDD or SSD. See: https://cloud.google.com/bigtable/pricing for more information.",
Default: "SSD",
Required: true,
Enum: map[interface{}]string{
"SSD": "SSD - Solid-state Drive",
"HDD": "HDD - Hard Disk Drive",
},
},
{
FieldName: "num_nodes",
Type: broker.JsonTypeString,
Details: "Number of nodes. See: https://cloud.google.com/bigtable/pricing for more information.",
Default: "3",
Required: true,
},
},
Examples: []broker.ServiceExample{
{
Name: "Basic Production Configuration",
Description: "Create an HDD production table and account that can manage and query the data.",
PlanId: "65a49268-2c73-481e-80f3-9fde5bd5a654",
ProvisionParams: map[string]interface{}{
"name": "orders-table",
},
BindParams: map[string]interface{}{
"role": "bigtable.user",
},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &BigTableBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/firestore/broker.go | pkg/providers/builtin/firestore/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 firestore
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
// FirestoreBroker is the service-broker back-end for creating and binding Firestore clients.
type FirestoreBroker struct {
base.BrokerBase
}
// Provision is a no-op call because only service accounts need to be bound/unbound for Firestore.
func (b *FirestoreBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
return models.ServiceInstanceDetails{}, nil
}
// Deprovision is a no-op call because only service accounts need to be bound/unbound for Firestore.
func (b *FirestoreBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
return nil, 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/providers/builtin/firestore/definition.go | pkg/providers/builtin/firestore/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 firestore
import (
"code.cloudfoundry.org/lager"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Firestore service.
func ServiceDefinition() *broker.ServiceDefinition {
// NOTE(jlewisiii) Firestore has some intentional differences from other services.
// First, it doesn't require legacy compatibility so we won't allow operators to override the whitelist.
// Second, Firestore uses the old datastore IAM role model so the roles will look strange.
return &broker.ServiceDefinition{
Id: "a2b7b873-1e34-4530-8a42-902ff7d66b43",
Name: "google-firestore",
Description: "Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL document database that simplifies storing, syncing, and querying data for your mobile, web, and IoT apps at global scale.",
DisplayName: "Google Cloud Firestore",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/firestore.svg",
DocumentationUrl: "https://cloud.google.com/firestore/docs/",
SupportUrl: "https://cloud.google.com/firestore/docs/getting-support",
Tags: []string{"gcp", "firestore", "preview", "beta"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "64403af0-4413-4ef3-a813-37f0306ef498",
Name: "default",
Description: "Firestore default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
BindInputVariables: accountmanagers.ServiceAccountWhitelistWithDefault([]string{"datastore.user", "datastore.viewer"}, "datastore.user"),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
BindComputedVariables: accountmanagers.ServiceAccountBindComputedVariables(),
Examples: []broker.ServiceExample{
{
Name: "Reader Writer",
Description: "Creates a general Firestore user and grants it permission to read and write entities.",
PlanId: "64403af0-4413-4ef3-a813-37f0306ef498",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
{
Name: "Read Only",
Description: "Creates a Firestore user that can only view entities.",
PlanId: "64403af0-4413-4ef3-a813-37f0306ef498",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{"role": "datastore.viewer"},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &FirestoreBroker{BrokerBase: bb}
},
IsBuiltin: 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/providers/builtin/account_managers/iam_test.go | pkg/providers/builtin/account_managers/iam_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 account_managers
import (
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1"
)
func TestIamMergeBindings(t *testing.T) {
table := map[string]struct {
input []*cloudresourcemanager.Binding
expect map[string][]string
}{
"combine matching roles": {
input: []*cloudresourcemanager.Binding{
{Role: "role-1", Members: []string{"m1"}},
{Role: "role-1", Members: []string{"m2"}},
},
expect: map[string][]string{
"role-1": {"m1", "m2"},
},
},
"deduplicates members": {
input: []*cloudresourcemanager.Binding{
{Role: "role-1", Members: []string{"m1"}},
{Role: "role-1", Members: []string{"m1"}},
},
expect: map[string][]string{
"role-1": {"m1"},
},
},
"removes roles with no members": {
input: []*cloudresourcemanager.Binding{
{Role: "role-1", Members: []string{}},
},
expect: map[string][]string{},
},
"does not merge different roles": {
input: []*cloudresourcemanager.Binding{
{Role: "role-1", Members: []string{"m1", "m2"}},
{Role: "role-2", Members: []string{"m1", "m3"}},
},
expect: map[string][]string{
"role-1": {"m1", "m2"},
"role-2": {"m1", "m3"},
},
},
}
for tn, tc := range table {
merged := mergeBindings(tc.input)
if len(merged) != len(tc.expect) {
t.Errorf("%s) expected %d merged bindings, got: %d", tn, len(tc.expect), len(merged))
}
for _, binding := range merged {
expset := utils.NewStringSet(tc.expect[binding.Role]...)
gotset := utils.NewStringSet(binding.Members...)
if !expset.Equals(gotset) {
t.Errorf("%s) expected %v members in %s role, got %v", tn, expset.ToSlice(), binding.Role, gotset.ToSlice())
}
}
}
}
func TestIamRemoveMemberFromBindings(t *testing.T) {
table := map[string]struct {
input []*cloudresourcemanager.Binding
expect map[string][]string
}{
"remove member from one role": {
input: []*cloudresourcemanager.Binding{
{Role: "role-1", Members: []string{"m1", "m2"}},
},
expect: map[string][]string{
"role-1": {"m2"},
},
},
"remove member from multiple roles": {
input: []*cloudresourcemanager.Binding{
{Role: "role-1", Members: []string{"m1", "m2"}},
{Role: "role-2", Members: []string{"m1", "m3"}},
},
expect: map[string][]string{
"role-1": {"m2"},
"role-2": {"m3"},
},
},
}
for tn, tc := range table {
updatedBindings := removeMemberFromBindings(tc.input, "m1")
if len(updatedBindings) != len(tc.expect) {
t.Errorf("%s) expected %d bindings, got: %d", tn, len(tc.expect), len(updatedBindings))
}
for _, binding := range updatedBindings {
expset := utils.NewStringSet(tc.expect[binding.Role]...)
gotset := utils.NewStringSet(binding.Members...)
if !expset.Equals(gotset) {
t.Errorf("%s) expected %v members in %s role, got %v", tn, expset.ToSlice(), binding.Role, gotset.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/pkg/providers/builtin/account_managers/iam.go | pkg/providers/builtin/account_managers/iam.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 account_managers
import (
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1"
)
// Merge multiple Bindings such that Bindings with the same Role result in
// a single Binding with combined Members
func mergeBindings(bindings []*cloudresourcemanager.Binding) []*cloudresourcemanager.Binding {
rb := []*cloudresourcemanager.Binding{}
for role, members := range rolesToMembersMap(bindings) {
if members.IsEmpty() {
continue
}
rb = append(rb, &cloudresourcemanager.Binding{
Role: role,
Members: members.ToSlice(),
})
}
return rb
}
// Map a role to a map of members, allowing easy merging of multiple bindings.
func rolesToMembersMap(bindings []*cloudresourcemanager.Binding) map[string]utils.StringSet {
bm := make(map[string]utils.StringSet)
for _, b := range bindings {
if set, ok := bm[b.Role]; ok {
set.Add(b.Members...)
} else {
bm[b.Role] = utils.NewStringSet(b.Members...)
}
}
return bm
}
// Remove a member from all role bindings to clean up the iam policy before deleting a service account.
func removeMemberFromBindings(bindings []*cloudresourcemanager.Binding, memberToRemove string) []*cloudresourcemanager.Binding {
for _, binding := range bindings {
for i, member := range binding.Members {
if member == memberToRemove {
binding.Members = append(binding.Members[:i], binding.Members[i+1:]...)
break
}
}
}
return bindings
}
| 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/providers/builtin/account_managers/service_account_manager.go | pkg/providers/builtin/account_managers/service_account_manager.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 account_managers
import (
"encoding/json"
"fmt"
"net/http"
"time"
"code.cloudfoundry.org/lager"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/validation"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"golang.org/x/net/context"
"golang.org/x/oauth2/jwt"
cloudres "google.golang.org/api/cloudresourcemanager/v1"
"google.golang.org/api/googleapi"
iam "google.golang.org/api/iam/v1"
)
const (
roleResourcePrefix = "roles/"
saResourcePrefix = "serviceAccount:"
projectResourcePrefix = "projects/"
)
type ServiceAccountManager struct {
ProjectId string
HttpConfig *jwt.Config
Logger lager.Logger
}
// If roleWhitelist is specified, then the extracted role is validated against it and an error is returned if
// the role is not contained within the whitelist
func (sam *ServiceAccountManager) CreateCredentials(ctx context.Context, vc *varcontext.VarContext) (map[string]interface{}, error) {
role := vc.GetString("role")
accountId := vc.GetString("service_account_name")
displayName := vc.GetString("service_account_display_name")
if err := vc.Error(); err != nil {
return nil, err
}
sam.Logger.Info("create-service-account", lager.Data{
"role": role,
"service_account_name": accountId,
"service_account_display_name": displayName,
})
// create and save account
newSA, err := sam.createServiceAccount(ctx, accountId, displayName)
if err != nil {
return nil, err
}
// adjust account permissions
// roles defined here: https://cloud.google.com/iam/docs/understanding-roles?hl=en_US#curated_roles
if err := sam.grantRoleToAccount(ctx, role, newSA); err != nil {
return nil, err
}
// create and save key
newSAKey, err := sam.createServiceAccountKey(ctx, newSA)
if err != nil {
return nil, fmt.Errorf("Error creating new service account key: %s", err)
}
newSAInfo := ServiceAccountInfo{
Name: newSA.DisplayName,
Email: newSA.Email,
UniqueId: newSA.UniqueId,
PrivateKeyData: newSAKey.PrivateKeyData,
ProjectId: sam.ProjectId,
}
return varcontext.Builder().MergeStruct(newSAInfo).BuildMap()
}
// deletes the given service account from Google
func (sam *ServiceAccountManager) DeleteCredentials(ctx context.Context, binding models.ServiceBindingCredentials) error {
var saCreds ServiceAccountInfo
if err := json.Unmarshal([]byte(binding.OtherDetails), &saCreds); err != nil {
return fmt.Errorf("Error unmarshalling credentials: %s", err)
}
iamService, err := iam.New(sam.HttpConfig.Client(ctx))
if err != nil {
return fmt.Errorf("Error creating IAM service: %s", err)
}
// Clean up account permissions
if err := sam.revokeRolesFromAccount(ctx, saCreds.Email); err != nil {
return fmt.Errorf("Error deleting role bindings from service account: %s", err)
}
resourceName := projectResourcePrefix + sam.ProjectId + "/serviceAccounts/" + saCreds.UniqueId
if _, err := iam.NewProjectsServiceAccountsService(iamService).Delete(resourceName).Do(); err != nil {
if gerr, ok := err.(*googleapi.Error); ok && gerr.Code == http.StatusNotFound {
return nil
}
return fmt.Errorf("Error deleting service account: %s", err)
}
return nil
}
func (sam *ServiceAccountManager) createServiceAccount(ctx context.Context, accountId, displayName string) (*iam.ServiceAccount, error) {
client := sam.HttpConfig.Client(ctx)
iamService, err := iam.New(client)
if err != nil {
return nil, fmt.Errorf("Error creating new IAM service: %s", err)
}
resourceName := projectResourcePrefix + sam.ProjectId
// create and save account
newSARequest := iam.CreateServiceAccountRequest{
AccountId: accountId,
ServiceAccount: &iam.ServiceAccount{
DisplayName: displayName,
},
}
return iam.NewProjectsServiceAccountsService(iamService).Create(resourceName, &newSARequest).Do()
}
func (sam *ServiceAccountManager) createServiceAccountKey(ctx context.Context, account *iam.ServiceAccount) (*iam.ServiceAccountKey, error) {
client := sam.HttpConfig.Client(ctx)
iamService, err := iam.New(client)
if err != nil {
return nil, fmt.Errorf("Error creating new IAM service: %s", err)
}
saKeyService := iam.NewProjectsServiceAccountsKeysService(iamService)
return saKeyService.Create(account.Name, &iam.CreateServiceAccountKeyRequest{}).Do()
}
func (sam *ServiceAccountManager) grantRoleToAccount(ctx context.Context, role string, account *iam.ServiceAccount) error {
client := sam.HttpConfig.Client(ctx)
cloudresService, err := cloudres.New(client)
if err != nil {
return fmt.Errorf("Error creating new cloud resource management service: %s", err)
}
for attempt := 0; attempt < 3; attempt++ {
currPolicy, err := cloudresService.Projects.GetIamPolicy(sam.ProjectId, &cloudres.GetIamPolicyRequest{}).Do()
if err != nil {
return fmt.Errorf("Error getting current project iam policy: %s", err)
}
currPolicy.Bindings = mergeBindings(append(currPolicy.Bindings, &cloudres.Binding{
Members: []string{saResourcePrefix + account.Email},
Role: roleResourcePrefix + role,
}))
newPolicyRequest := cloudres.SetIamPolicyRequest{
Policy: currPolicy,
}
_, err = cloudresService.Projects.SetIamPolicy(sam.ProjectId, &newPolicyRequest).Do()
if err == nil {
return nil
}
if isConflictError(err) {
time.Sleep(5 * time.Second)
continue
} else {
return fmt.Errorf("Error assigning policy to service account: %s", err)
}
}
return err
}
func (sam *ServiceAccountManager) revokeRolesFromAccount(ctx context.Context, email string) error {
client := sam.HttpConfig.Client(ctx)
cloudresService, err := cloudres.New(client)
if err != nil {
return fmt.Errorf("Error creating new cloud resource management service: %s", err)
}
for attempt := 0; attempt < 3; attempt++ {
currPolicy, err := cloudresService.Projects.GetIamPolicy(sam.ProjectId, &cloudres.GetIamPolicyRequest{}).Do()
if err != nil {
return fmt.Errorf("Error getting current project iam policy: %s", err)
}
currPolicy.Bindings = mergeBindings(removeMemberFromBindings(currPolicy.Bindings, saResourcePrefix+email))
newPolicyRequest := cloudres.SetIamPolicyRequest{
Policy: currPolicy,
}
_, err = cloudresService.Projects.SetIamPolicy(sam.ProjectId, &newPolicyRequest).Do()
if err == nil {
return nil
}
if isConflictError(err) {
time.Sleep(5 * time.Second)
continue
} else {
return fmt.Errorf("Error updating iam policy: %s", err)
}
}
return err
}
func isConflictError(err error) bool {
gerr, ok := err.(*googleapi.Error)
return ok && gerr != nil && gerr.Code == 409
}
type ServiceAccountInfo struct {
// the bits to save
Name string `json:"Name"`
Email string `json:"Email"`
UniqueId string `json:"UniqueId"`
ProjectId string `json:"ProjectId"`
// the bit to return
PrivateKeyData string `json:"PrivateKeyData"`
}
// ServiceAccountWhitelistWithDefault holds non-overridable whitelists with default values.
func ServiceAccountWhitelistWithDefault(whitelist []string, defaultValue string) []broker.BrokerVariable {
whitelistEnum := make(map[interface{}]string)
for _, val := range whitelist {
whitelistEnum[val] = roleResourcePrefix + val
}
return []broker.BrokerVariable{
{
FieldName: "role",
Type: broker.JsonTypeString,
Details: `The role for the account without the "roles/" prefix. See: https://cloud.google.com/iam/docs/understanding-roles for more details.`,
Enum: whitelistEnum,
Default: defaultValue,
},
}
}
// ServiceAccountBindComputedVariables holds computed variables required to provision service accounts, label them and ensure they are unique.
func ServiceAccountBindComputedVariables() []varcontext.DefaultVariable {
return []varcontext.DefaultVariable{
// XXX names are truncated to 20 characters because of a bug in the IAM service
{Name: "service_account_name", Default: `${str.truncate(20, "pcf-binding-${request.binding_id}")}`, Overwrite: true},
{Name: "service_account_display_name", Default: "${service_account_name}", Overwrite: true},
}
}
// FixedRoleBindComputedVariables allows you to create a service account with a
// fixed role.
func FixedRoleBindComputedVariables(role string) []varcontext.DefaultVariable {
fixedRoleVar := varcontext.DefaultVariable{Name: "role", Default: role, Overwrite: true}
return append(ServiceAccountBindComputedVariables(), fixedRoleVar)
}
// Variables output by all brokers that return service account info
func ServiceAccountBindOutputVariables() []broker.BrokerVariable {
return []broker.BrokerVariable{
{
FieldName: "Email",
Type: broker.JsonTypeString,
Details: "Email address of the service account.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("pcf-binding-ex312029@my-project.iam.gserviceaccount.com").
Pattern(`^pcf-binding-[a-z0-9-]+@.+\.gserviceaccount\.com$`).
Build(),
},
{
FieldName: "Name",
Type: broker.JsonTypeString,
Details: "The name of the service account.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("pcf-binding-ex312029").
Build(),
},
{
FieldName: "PrivateKeyData",
Type: broker.JsonTypeString,
Details: "Service account private key data. Base64 encoded JSON.",
Required: true,
Constraints: validation.NewConstraintBuilder().
MinLength(512). // absolute lower bound
Pattern(`^[A-Za-z0-9+/]*=*$`). // very rough Base64 regex
Build(),
},
{
FieldName: "ProjectId",
Type: broker.JsonTypeString,
Details: "ID of the project that owns the service account.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("my-project").
Pattern(`^[a-z0-9-]+$`).
MinLength(6).
MaxLength(30).
Build(),
},
{
FieldName: "UniqueId",
Type: broker.JsonTypeString,
Details: "Unique and stable ID of the service account.",
Required: true,
Constraints: validation.NewConstraintBuilder().
Examples("112447814736626230844").
Build(),
},
}
}
| 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/providers/builtin/account_managers/service_account_manager_test.go | pkg/providers/builtin/account_managers/service_account_manager_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 account_managers
import (
"reflect"
"testing"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
)
func TestServiceAccountWhitelistWithDefault(t *testing.T) {
details := `The role for the account without the "roles/" prefix. See: https://cloud.google.com/iam/docs/understanding-roles for more details.`
cases := map[string]struct {
Whitelist []string
DefaultRole string
Expected broker.BrokerVariable
}{
"default in whitelist": {
Whitelist: []string{"foo"},
DefaultRole: "foo",
Expected: broker.BrokerVariable{
FieldName: "role",
Type: broker.JsonTypeString,
Details: details,
Required: false,
Default: "foo",
Enum: map[interface{}]string{"foo": "roles/foo"},
},
},
"default not in whitelist": {
Whitelist: []string{"foo"},
DefaultRole: "test",
Expected: broker.BrokerVariable{
FieldName: "role",
Type: broker.JsonTypeString,
Details: details,
Required: false,
Default: "test",
Enum: map[interface{}]string{"foo": "roles/foo"},
},
},
}
for tn, tc := range cases {
t.Run(tn, func(t *testing.T) {
vars := ServiceAccountWhitelistWithDefault(tc.Whitelist, tc.DefaultRole)
if len(vars) != 1 {
t.Fatalf("Expected 1 input variable, got %d", len(vars))
}
if !reflect.DeepEqual(vars[0], tc.Expected) {
t.Fatalf("Expected %#v, got %#v", tc.Expected, vars[0])
}
})
}
}
| 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/providers/builtin/dialogflow/broker.go | pkg/providers/builtin/dialogflow/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 dialogflow
import (
"context"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/db_service/models"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/varcontext"
"github.com/pivotal-cf/brokerapi"
)
// DialogflowBroker is the service-broker back-end for creating and binding Dialogflow clients.
type DialogflowBroker struct {
base.BrokerBase
}
// Provision is a no-op call because only service accounts need to be bound/unbound for Dialogflow.
func (b *DialogflowBroker) Provision(ctx context.Context, provisionContext *varcontext.VarContext) (models.ServiceInstanceDetails, error) {
return models.ServiceInstanceDetails{}, nil
}
// Deprovision is a no-op call because only service accounts need to be bound/unbound for Dialogflow.
func (b *DialogflowBroker) Deprovision(ctx context.Context, instance models.ServiceInstanceDetails, details brokerapi.DeprovisionDetails) (*string, error) {
return nil, 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/providers/builtin/dialogflow/definition.go | pkg/providers/builtin/dialogflow/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 dialogflow
import (
"code.cloudfoundry.org/lager"
accountmanagers "github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/account_managers"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/providers/builtin/base"
"github.com/GoogleCloudPlatform/gcp-service-broker/pkg/broker"
"github.com/pivotal-cf/brokerapi"
"golang.org/x/oauth2/jwt"
)
// ServiceDefinition creates a new ServiceDefinition object for the Dialogflow service.
func ServiceDefinition() *broker.ServiceDefinition {
return &broker.ServiceDefinition{
Id: "e84b69db-3de9-4688-8f5c-26b9d5b1f129",
Name: "google-dialogflow",
Description: "Dialogflow is an end-to-end, build-once deploy-everywhere development suite for creating conversational interfaces for websites, mobile applications, popular messaging platforms, and IoT devices.",
DisplayName: "Google Cloud Dialogflow",
ImageUrl: "https://cloud.google.com/_static/images/cloud/products/logos/svg/dialogflow-enterprise.svg",
DocumentationUrl: "https://cloud.google.com/dialogflow-enterprise/docs/",
SupportUrl: "https://cloud.google.com/dialogflow-enterprise/docs/support",
Tags: []string{"gcp", "dialogflow", "preview"},
Bindable: true,
PlanUpdateable: false,
Plans: []broker.ServicePlan{
{
ServicePlan: brokerapi.ServicePlan{
ID: "3ac4e1bd-b22d-4a99-864b-d3a3ac582348",
Name: "default",
Description: "Dialogflow default plan.",
Free: brokerapi.FreeValue(false),
},
ServiceProperties: map[string]string{},
},
},
ProvisionInputVariables: []broker.BrokerVariable{},
BindInputVariables: []broker.BrokerVariable{},
BindComputedVariables: accountmanagers.FixedRoleBindComputedVariables("dialogflow.client"),
BindOutputVariables: accountmanagers.ServiceAccountBindOutputVariables(),
Examples: []broker.ServiceExample{
{
Name: "Reader",
Description: "Creates a Dialogflow user and grants it permission to detect intent and read/write session properties (contexts, session entity types, etc.).",
PlanId: "3ac4e1bd-b22d-4a99-864b-d3a3ac582348",
ProvisionParams: map[string]interface{}{},
BindParams: map[string]interface{}{},
},
},
ProviderBuilder: func(projectId string, auth *jwt.Config, logger lager.Logger) broker.ServiceProvider {
bb := base.NewBrokerBase(projectId, auth, logger)
return &DialogflowBroker{BrokerBase: bb}
},
IsBuiltin: 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/toggles/toggle.go | pkg/toggles/toggle.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 defines a standard way to define, list, and use feature
toggles in the service broker.
It mimics Go's `flags` package, but uses Viper as a backing store to abstract
out how a particular flag is set.
*/
package toggles
import (
"sort"
"github.com/GoogleCloudPlatform/gcp-service-broker/utils"
"github.com/spf13/viper"
)
// Features is the default set of flags for enabling different features.
// For legacy compatibility reasons the flags are put under the "compatibility"
// namespace.
var Features = NewToggleSet("compatibility.")
// Toggle represents a single feature that the user can enable or disable.
type Toggle struct {
Name string
Default bool
Description string
propertyPrefix string
}
// EnvironmentVariable gets the environment variable used to control the toggle.
func (toggle Toggle) EnvironmentVariable() string {
return utils.PropertyToEnv(toggle.viperProperty())
}
// viperProperty gets the viper property of the variable to control the toggle.
func (toggle Toggle) viperProperty() string {
return toggle.propertyPrefix + toggle.Name
}
// IsActive returns true if the toggle is enabled and false if it isn't.
func (toggle Toggle) IsActive() bool {
return viper.GetBool(toggle.viperProperty())
}
// A ToggleSet represents a set of defined toggles. The zero value of a ToggleSet
// has no property prefix.
type ToggleSet struct {
toggles []Toggle
propertyPrefix string
}
// Toggles returns a list of all registered toggles sorted lexicographically by
// their property name.
func (set *ToggleSet) Toggles() []Toggle {
var copy []Toggle
for _, tgl := range set.toggles {
copy = append(copy, tgl)
}
sort.Slice(copy, func(i, j int) bool { return copy[i].Name < copy[j].Name })
return copy
}
// Toggle creates a new toggle with the given name, default value, label and description.
// It also adds the toggle to an internal registry and initializes the default value in viper.
func (set *ToggleSet) Toggle(name string, value bool, description string) Toggle {
toggle := Toggle{
Name: name,
Default: value,
Description: description,
propertyPrefix: set.propertyPrefix,
}
set.toggles = append(set.toggles, toggle)
viper.SetDefault(toggle.viperProperty(), value)
return toggle
}
// NewFlagSet returns a new, empty toggle set with the specified property prefix.
// The property prefix will be prepended to any toggles exactly as-is. You MUST
// specify a trailing period if you want your properties to be namespaced.
func NewToggleSet(propertyPrefix string) *ToggleSet {
return &ToggleSet{
propertyPrefix: propertyPrefix,
}
}
| go | Apache-2.0 | 2f676b434e3f9d570f3b1d831f81e3a3de8c7664 | 2026-01-07T09:45:07.005916Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.