Skip to content
This repository has been archived by the owner on May 3, 2022. It is now read-only.

Enable custom actions on existing claims or bundles #870

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion cmd/duffle/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ func (ex *exportCmd) setup() (string, loader.BundleLoader, error) {
}

func resolveBundleFilePath(bun, homePath string, bundleIsFile bool) (string, error) {

if bundleIsFile {
return bun, nil
}
Expand Down
243 changes: 164 additions & 79 deletions cmd/duffle/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,107 +3,192 @@ package main
import (
"fmt"
"io"
"log"

"github.com/spf13/cobra"

"github.com/deislabs/cnab-go/action"
"github.com/deislabs/cnab-go/claim"
)

func newRunCmd(w io.Writer) *cobra.Command {
const short = "run a target in the bundle"
const long = `Run an arbitrary target in the bundle.
type runCmd struct {
action string
claimName string
bundleName string
bundlePath string

relocationMapping string
credentialsFiles []string
valuesFile string
setParams []string
setFiles []string

driver string
out io.Writer
opOutFunc action.OperationConfigFunc

home string
storage *claim.Store
claim *claim.Claim
}

Some CNAB bundles may declare custom targets in addition to install, upgrade, and uninstall.
This command can be used to execute those targets.
func newRunCmd(w io.Writer) *cobra.Command {
const short = "run an action in the bundle"
const long = `Run an arbitrary action in the bundle.

The 'run' command takes a ACTION and a RELEASE NAME:
Some CNAB bundles may declare custom actions in addition to install, upgrade, and uninstall.
This command can be used to execute those actions.

$ duffle run migrate my-release
The 'run' command takes an ACTION and a CLAIM name:

This will start the invocation image for the release in 'my-release', and then send
the action 'migrate'. If the invocation image does not have a 'migrate' action, it
may return an error.
$ duffle run migrate --claim myExistingClaim
or
$ duffle run preinstall --bundle myBundle --claim myNewClaim
or
$ duffle run preinstall --bundle-is-file path/to/bundle.json --claim myNewClaim

Custom actions can only be executed on releases (already-installed bundles).
All custom actions can be executed on claims (installed bundles).
Stateless custom actions can be executed on claims or bundles.
A new claim will be created if a bundle is specified and the action modifies.

Credentials and parameters may be passed to the bundle during a target action.
Credentials and parameters may also be passed in.
`
var (
driver string
credentialsFiles []string
valuesFile string
setParams []string
setFiles []string
relocationMapping string
)

run := &runCmd{out: w}
cmd := &cobra.Command{
Use: "run ACTION RELEASE_NAME",
Use: "run ACTION --claim CLAIM [--bundle BUNDLE | --bundle-is-file path/to/bundle.json]",
Aliases: []string{"exec"},
Short: short,
Long: long,
Args: cobra.ExactArgs(2),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
target := args[0]
claimName := args[1]
storage := claimStorage()
c, err := storage.Read(claimName)
if err != nil {
if err == claim.ErrClaimNotFound {
return fmt.Errorf("Bundle installation '%s' not found", claimName)
}
return err
}

creds, err := loadCredentials(credentialsFiles, c.Bundle)
if err != nil {
return err
}

driverImpl, err := prepareDriver(driver)
if err != nil {
return err
}

// Override parameters only if some are set.
if valuesFile != "" || len(setParams) > 0 {
c.Parameters, err = calculateParamValues(c.Bundle, valuesFile, setParams, setFiles)
if err != nil {
return err
}
}

opRelocator, err := makeOpRelocator(relocationMapping)
if err != nil {
return err
}

action := &action.RunCustom{
Driver: driverImpl,
Action: target,
}

fmt.Fprintf(w, "Executing custom action %q for release %q", target, claimName)
err = action.Run(&c, creds, setOut(cmd.OutOrStdout()), opRelocator)
if actionDef := c.Bundle.Actions[target]; !actionDef.Modifies {
// Do not store a claim for non-mutating actions.
return err
}

err2 := storage.Store(c)
if err != nil {
return fmt.Errorf("run failed: %s", err)
}
return err2
run.action = args[0]
run.home = homePath()
return run.run()
},
}
run.opOutFunc = setOut(cmd.OutOrStdout())

flags := cmd.Flags()
flags.StringVarP(&driver, "driver", "d", "docker", "Specify a driver name")
flags.StringVarP(&relocationMapping, "relocation-mapping", "m", "", "Path of relocation mapping JSON file")
flags.StringArrayVarP(&credentialsFiles, "credentials", "c", []string{}, "Specify a set of credentials to use inside the CNAB bundle")
flags.StringVarP(&valuesFile, "parameters", "p", "", "Specify file containing parameters. Formats: toml, MORE SOON")
flags.StringArrayVarP(&setParams, "set", "s", []string{}, "Set individual parameters as NAME=VALUE pairs")
flags.StringVarP(&run.claimName, "claim", "i", "", "Specify the name of an existing claim (required)")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this always an existing claim?

flags.StringVarP(&run.bundleName, "bundle", "b", "", "Specify the name of a bundle")
flags.StringVarP(&run.bundlePath, "bundle-is-file", "f", "", "Specify the path to a bundle.json")
flags.StringVarP(&run.driver, "driver", "d", "docker", "Specify a driver name")
flags.StringVarP(&run.relocationMapping, "relocation-mapping", "m", "", "Path of relocation mapping JSON file")
flags.StringArrayVarP(&run.credentialsFiles, "credentials", "c", []string{}, "Specify a set of credentials to use inside the CNAB bundle")
flags.StringVarP(&run.valuesFile, "parameters", "p", "", "Specify file containing parameters. Formats: toml, MORE SOON")
flags.StringArrayVarP(&run.setParams, "set", "s", []string{}, "Set individual parameters as NAME=VALUE pairs")

err := cmd.MarkFlagRequired("claim")
if err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: in duffle, it's more usual to fold assignments and if statements together when no new variables need to last beyond the scope of the if.

log.Fatal("required flag \"claim\" is missing")
}

return cmd
}

func (r *runCmd) run() error {
if r.storage == nil {
storage := claimStorage()
r.storage = &storage
}

err := r.prepareClaim()
if err != nil {
return fmt.Errorf("failed to prepare claim %q: %s", r.claimName, err)
}

creds, err := loadCredentials(r.credentialsFiles, r.claim.Bundle)
if err != nil {
return err
}

driver, err := prepareDriver(r.driver)
if err != nil {
return fmt.Errorf("failed to prepare driver %q: %s", r.driver, err)
}

// Override parameters only if some are set.
if r.valuesFile != "" || len(r.setParams) > 0 {
r.claim.Parameters, err = calculateParamValues(r.claim.Bundle, r.valuesFile, r.setParams, r.setFiles)
if err != nil {
return fmt.Errorf("failed to set parameters on claim: %s", err)
}
}

opRelocator, err := makeOpRelocator(r.relocationMapping)
if err != nil {
return err
}

action := &action.RunCustom{
Driver: driver,
Action: r.action,
}

fmt.Fprintf(r.out, "Executing custom action %q\n", r.action)
err = action.Run(r.claim, creds, r.opOutFunc, opRelocator)
if actionDef := r.claim.Bundle.Actions[r.action]; !actionDef.Modifies {
// Do not store a claim for non-mutating actions.
return err
}

storageErr := r.storage.Store(*r.claim)
if err != nil {
return fmt.Errorf("run failed: %s", err)
}

return storageErr
}

func (r *runCmd) prepareClaim() error {
var err error

if r.bundleName != "" && r.bundlePath != "" {
return fmt.Errorf("cannot specify both --bundle and --bundle-is-file: received bundle %q and bundle file %q", r.bundleName, r.bundlePath)
}

if r.bundleName != "" {
r.bundlePath, err = resolveBundleFilePath(r.bundleName, r.home, false)
if err != nil {
return err
}
}

if r.bundlePath != "" {
return r.createClaimFromBundlePath()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens here if a claim already exists?

}

return r.useExistingClaim()
}

func (r *runCmd) createClaimFromBundlePath() error {
if !fileExists(r.bundlePath) {
return fmt.Errorf("bundle file %q does not exist", r.bundlePath)
}

bundle, err := loadBundle(r.bundlePath)
if err != nil {
return fmt.Errorf("failed to parse contents in bundle file %q: %s", r.bundlePath, err)
}

r.claim, err = claim.New(r.claimName)
if err != nil {
return fmt.Errorf("failed to create claim %q: %s", r.claimName, err)
}

r.claim.Bundle = bundle
return nil
}

func (r *runCmd) useExistingClaim() error {
c, err := r.storage.Read(r.claimName)
if err != nil {
if err == claim.ErrClaimNotFound {
return fmt.Errorf("claim %q not found in duffle store", r.claimName)
}
return fmt.Errorf("failed to read claim %q from duffle store: %s", r.claimName, err)
}

r.claim = &c
return nil
}
Loading