deployment

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2019 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

The deployment packages implements functionality for deploying projects to GCP. This includes sorting deployment configurations in dependency order, and executing GCP API calls through the gcloud tool.

Index

Constants

View Source
const (
	// ApplyAction passed as "action" parameter value to cmd.execute(action string, ...) to apply Deployment created or updated in preview mode.
	ActionApply string = "apply"
	// ApplyAction passed as "action" parameter value to cmd.execute(action string, ...) to delete Deployment.
	ActionDelete string = "delete"
	// ApplyAction passed as "action" parameter value to cmd.execute(action string, ...) to update Deployment.
	ActionCreate string = "create"
	// ApplyAction passed as "action" parameter value to cmd.execute(action string, ...) to update Deployment.
	ActionUpdate string = "update"
)

Variables

View Source
var DefaultProjectID string

DefaultProjectID holds default GCP project ID, it used in case project ID not provided in configuration file, see common.setDefaultProjectID for variable initialization details.

View Source
var RunGCloud = func(args ...string) (result string, err error) {
	log.Println("gcloud", strings.Join(args, " "))
	cmd := exec.Command("gcloud", args...)

	cmd.Env = append(cmd.Env, fmt.Sprintf("PATH=%s", os.Getenv("PATH")))

	output, err := cmd.CombinedOutput()

	if err != nil {
		return string(output), err
	}

	return string(output), err
}

The RunGCloud function runs the gcloud tool with the specified arguments. It is implemented as a variable so that it can be mocked in tests of its exported consumers.

Functions

func AppendMap

func AppendMap(a map[string]string, b map[string]string) map[string]string

AppendMap appends string map B to map A, returns A

func ApplyPreview

func ApplyPreview(deployment *Deployment) (string, error)

ApplyPreview function apply changes made before with --preview flag

func CancelPreview

func CancelPreview(deployment *Deployment) (string, error)

CancelPreview cancels update/create/delete action, created with review flag. Function uses gcloud deployments cancel-preview command. In case of cancellation of preview of create action, required deployment and run Delete() after CancelPreview() for cleanup.

func Create

func Create(deployment *Deployment, preview bool) (string, error)

Create creates deployment based on passed Deployment object passed into it. Create initialize passed Deployment object with Outputs map in case of successful creation and return error otherwise. preview parameter define if deployment should be created in 'Preview' mode. Function returns gcloud cli raw output for debug purposes both in case of success and error.

func Delete

func Delete(deployment *Deployment, preview bool) (string, error)

Delete function removed Deployment passed into it as parameter. Boolean preview param define if changes have to be previewed before apply.

func DeploymentNameFromFile

func DeploymentNameFromFile(path string) string

DeploymentNameFromFile creates valid deployment name from file path satisfied Deployment resource "name" field requirements: Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. Function cuts forbidden characters at the end and start of a name also it truncates name up to 63 characters. see more https://cloud.google.com/deployment-manager/docs/reference/latest/deployments#resource

func GCloudDefaultProjectID

func GCloudDefaultProjectID() (string, error)

GCloudDefaultProjectID returns the default project id taken from local gcloud configuration.

func GetOutputs

func GetOutputs(project string, name string) (map[string]interface{}, error)

GetOutputs retrieves existing Deployment outputs using gcloud and store result in map[string]interface{} where "resourceName.propertyName" is key, and value is string (in case of flat value) or JSON object.

func GetUserInput

func GetUserInput(message string, options []string, rd io.Reader) string

GetUserInput asks for user input and validate entered value is equal to one of the provided options. Returns validated option string

func IsYAML

func IsYAML(text string) bool

IsYAML checks if text parameter passed if YAML string.

func Order

func Order(configs map[string]Config) ([][]Config, error)

Order function receives map of configs with Config.FullName() string as a key, find dependencies between them, and order them topologically using directed graph. Returns array of arrays of config, each inner array represent configs that could be created in parallel each next level depends on previous

func ReparentPath

func ReparentPath(baseDir string, file string) string

Function ReparentPath used to create absolute path for config "import" entries. Absolute path composed by ReparentPath function from config file path base folder concatenated with import statement value. This transformation needed to make deployment YAML config file location independent, after import "absolutisation" deployment config might be copied to any location (as current CFT cli will copy its copy to tmp folder. Examples:

/base/folder/config.yaml and ../script.py will concatenate to /base/script.py
/base/folder/config.yaml and /base/folder/script.py will concatenate to /base/folder/script.py as long path already absolute

func Update

func Update(deployment *Deployment, preview bool) (string, error)

Update updates deployment based on passed Deployment object passed into it. Update initialize passed Deployment object with Outputs map in case of successful creation and return error otherwise. preview parameter define if deployment should be updated in 'Preview' mode. Function returns gcloud cli raw output for debug purposes both in case of success and error.

Types

type Config

type Config struct {
	// Name field contains Deployment Name it could be initialized from
	// config YAML field and if it missing in YAML, from config YAML file name itself.
	Name string
	// Project field contains GCP Project Id it could be initialized from config YAML, env variable, gcloud default.
	// Note: don't access this member directly, use GetProjectID instead.
	Project string
	// Deployment string contains GCP Deployment description it not required and can be empty.
	Description string
	// Imports struct contains all "import" entries from config YAML file.
	Imports []struct {
		// Name of the import statement.
		Name string
		// Path to import file, can be relative or absolute.
		Path string
	}
	// Resources map contains all Deployment Resources, listed in deployment config YAML file.
	// TODO explain what value used as map key
	Resources []map[string]interface{}
	// contains filtered or unexported fields
}

Config struct keep config data parsed from passed config YAML.

func NewConfig

func NewConfig(data string, file string) Config

The Config type represents configuration data parsed from YAML.

func (Config) FullName

func (c Config) FullName() string

FullName returns a name for the configuration that is intended to be unique. The name is in the format "ProjectName.DeploymentName" and may be used as a map key.

func (Config) GetProject

func (c Config) GetProject() string

GetProject returns project id if it set in config file, otherwise default value defined in DefaultProjectID var.

func (Config) Source

func (c Config) Source() string

Source returns the the path of the file for a file-backed configuration, or a YAML string for YAML configurations.

func (Config) String

func (c Config) String() string

String implements fmt.Stringer for the Config type.

func (Config) YAML

func (c Config) YAML(outputs map[string]map[string]interface{}) ([]byte, error)

YAML function marshals a Config object to YAML. It sets all relative import paths to absolute paths and removes all custom elements that the gcloud deployment manager is not aware of, including name, project, and description. output param contains map of map with Outputs variables of all Deployments created/updated by current cli run, where key of first map is project.deployment names and map[string]interface{} - map of Deployment output properties names->values. YAML returns byte array of config with output references substituted by real values from outputs parameter map.

type Deployment

type Deployment struct {
	// Outputs map contains deployment outputs values in form resourceName.proeprtyName: value, map filled with data
	// after deployment update/create operation. Value could be either plain string or complex object.
	Outputs map[string]interface{}
	// contains filtered or unexported fields
}

The Deployment type represents a real GCP Deployment entity that is either already created, or yet-to-be created.

func NewDeployment

func NewDeployment(config Config, outputs map[string]map[string]interface{}, processConfig bool) *Deployment

NewDeployment creates a new Deployment object, overriding all outward references. In effect, this means all deployment dependencies must exist in the GCP project. output parameter is map of maps where key is Deployment full name (project_name.deployment_name), and value is map of corresponding Deployment outputs properties.

func (*Deployment) Execute

func (d *Deployment) Execute(action string, preview bool) (output string, error error)

Executes executes create/update/delete actions and returns Deployment status.

func (Deployment) FullName

func (d Deployment) FullName() string

FullName function is the same as deployment.Config.FullName(), can be used in map[string]Deployment as a key.

func (Deployment) String

func (d Deployment) String() string

String implements fmt.Stringer for the Deployment type.

type DeploymentDescription

type DeploymentDescription struct {
	Deployment struct {
		Name      string
		Operation struct {
			OperationType string
			Status        string
		}
	}
	Resources []DeploymentDescriptionResource
}

func GetDeploymentDescription

func GetDeploymentDescription(name string, project string) (*DeploymentDescription, error)

type DeploymentDescriptionResource

type DeploymentDescriptionResource struct {
	Name            string
	Type            string
	Properties      string
	FinalProperties string `yaml:",omitempty"`
	Update          struct {
		Properties      string
		FinalProperties string `yaml:",omitempty"`
		State           string
	} `yaml:",omitempty"`
}

type Resources

type Resources struct {
	Name    string
	Outputs []struct {
		Value interface{} `yaml:"finalValue"`
		Name  string
	}
	Resources []Resources
}

Resource struct used to parse deployment manifest yaml received with 'gcloud deployment-manager manifests describe' command.

type Status

type Status int

Status represent Deployment status in enum/numerical format

const (
	// Done Status represent successfully finished Deployment state.
	Done Status = 0
	// Pending Status means Deployment in "PENDING" state, means resource creation process not started yet.
	Pending Status = 1
	// Pending Status means Deployment in "RUNNING" state, means resource creation process started.
	Running Status = 2
	// NotFound Status means Deployment is not exists in any state.
	NotFound Status = 3
	// Error Status means Deployment is failed or deployment describe operation itself completed with error.
	Error Status = 4
)

func GetStatus

func GetStatus(deployment *Deployment) (Status, error)

GetStatus retrieves Deployment status using gcloud cli, see deployment.Status type for details.

func (Status) String

func (s Status) String() string

String returns human readable string representation of Deployment Status.

Jump to

Keyboard shortcuts

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