Skip to content

Commit

Permalink
More exit codes (rancher#376)
Browse files Browse the repository at this point in the history
Use elemental-error in new, run-stage, pull-image, cloud-init, convert-disk and build-iso commands.

Fixes rancher#366, rancher#369, rancher#367, rancher#363, rancher#364, rancher#361

If duplicate exit-codes are used in pkg/errors/exit-codes.go the `make
build_docs` will now exit with an error.

Signed-off-by: Fredrik Lönnegren <[email protected]>
  • Loading branch information
frelon authored Nov 18, 2022
1 parent 4fcd85b commit d145f9f
Show file tree
Hide file tree
Showing 10 changed files with 133 additions and 73 deletions.
35 changes: 17 additions & 18 deletions cmd/build-iso.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/rancher/elemental-cli/cmd/config"
"github.com/rancher/elemental-cli/pkg/action"
"github.com/rancher/elemental-cli/pkg/constants"
elementalError "github.com/rancher/elemental-cli/pkg/error"
v1 "github.com/rancher/elemental-cli/pkg/types/v1"
"github.com/rancher/elemental-cli/pkg/utils"
)
Expand All @@ -52,19 +53,20 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
path, err := exec.LookPath("mount")
if err != nil {
return err
return elementalError.NewFromError(err, elementalError.StatFile)
}
mounter := mount.New(path)

cfg, err := config.ReadConfigBuild(viper.GetString("config-dir"), cmd.Flags(), mounter)
if err != nil {
cfg.Logger.Errorf("Error reading config: %s\n", err)
return elementalError.NewFromError(err, elementalError.ReadingBuildConfig)
}

flags := cmd.Flags()
err = validateCosignFlags(cfg.Logger, flags)
if err != nil {
return err
return elementalError.NewFromError(err, elementalError.CosignWrongFlags)
}

// Set this after parsing of the flags, so it fails on parsing and prints usage properly
Expand All @@ -73,20 +75,20 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command {
spec, err := config.ReadBuildISO(cfg, flags)
if err != nil {
cfg.Logger.Errorf("invalid install command setup %v", err)
return err
return elementalError.NewFromError(err, elementalError.ReadingSpecConfig)
}

if len(args) == 1 {
imgSource, err := v1.NewSrcFromURI(args[0])
if err != nil {
cfg.Logger.Errorf("not a valid rootfs source image argument: %s", args[0])
return err
return elementalError.NewFromError(err, elementalError.IdentifySource)
}
spec.RootFS = []*v1.ImageSource{imgSource}
} else if len(spec.RootFS) == 0 {
errmsg := "rootfs source image for building ISO was not provided"
cfg.Logger.Errorf(errmsg)
return fmt.Errorf(errmsg)
return elementalError.New(errmsg, elementalError.NoSourceProvided)
}

// Repos and overlays can't be unmarshaled directly as they require
Expand All @@ -100,24 +102,27 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command {
if ok, err := utils.Exists(cfg.Fs, oRootfs); ok {
spec.RootFS = append(spec.RootFS, v1.NewDirSrc(oRootfs))
} else {
cfg.Logger.Errorf("Invalid value for overlay-rootfs")
return fmt.Errorf("Invalid path '%s': %v", oRootfs, err)
msg := fmt.Sprintf("Invalid path '%s': %v", oRootfs, err)
cfg.Logger.Errorf(msg)
return elementalError.New(msg, elementalError.StatFile)
}
}
if oUEFI != "" {
if ok, err := utils.Exists(cfg.Fs, oUEFI); ok {
spec.UEFI = append(spec.UEFI, v1.NewDirSrc(oUEFI))
} else {
cfg.Logger.Errorf("Invalid value for overlay-uefi")
return fmt.Errorf("Invalid path '%s': %v", oUEFI, err)
msg := fmt.Sprintf("Invalid path '%s': %v", oUEFI, err)
cfg.Logger.Errorf(msg)
return elementalError.New(msg, elementalError.StatFile)
}
}
if oISO != "" {
if ok, err := utils.Exists(cfg.Fs, oISO); ok {
spec.Image = append(spec.Image, v1.NewDirSrc(oISO))
} else {
cfg.Logger.Errorf("Invalid value for overlay-iso")
return fmt.Errorf("Invalid path '%s': %v", oISO, err)
msg := fmt.Sprintf("Invalid path '%s': %v", oISO, err)
cfg.Logger.Errorf(msg)
return elementalError.New(msg, elementalError.StatFile)
}
}

Expand All @@ -126,13 +131,7 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command {
}

buildISO := action.NewBuildISOAction(cfg, spec)
err = buildISO.ISORun()
if err != nil {
cfg.Logger.Errorf(err.Error())
return err
}

return nil
return buildISO.ISORun()
},
}

Expand Down
9 changes: 6 additions & 3 deletions cmd/cloud-init.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"k8s.io/mount-utils"

"github.com/rancher/elemental-cli/cmd/config"
elementalError "github.com/rancher/elemental-cli/pkg/error"

"github.com/mudler/yip/pkg/schema"
"github.com/spf13/cobra"
Expand All @@ -40,8 +41,9 @@ func NewCloudInitCmd(root *cobra.Command) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), &mount.FakeMounter{})
if err != nil {
return err
return elementalError.NewFromError(err, elementalError.ReadingRunConfig)
}

stage, _ := cmd.Flags().GetString("stage")
dot, _ := cmd.Flags().GetBool("dotnotation")

Expand All @@ -54,13 +56,14 @@ func NewCloudInitCmd(root *cobra.Command) *cobra.Command {
if fromStdin {
std, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return err
return elementalError.NewFromError(err, elementalError.ReadFile)
}

args = []string{string(std)}
}

return cfg.CloudInitRunner.Run(stage, args...)
err = cfg.CloudInitRunner.Run(stage, args...)
return elementalError.NewFromError(err, elementalError.CloudInitRunStage)
},
}
root.AddCommand(c)
Expand Down
15 changes: 9 additions & 6 deletions cmd/convert-disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ import (
"fmt"
"strings"

"github.com/rancher/elemental-cli/cmd/config"
"github.com/rancher/elemental-cli/pkg/action"
"github.com/rancher/elemental-cli/pkg/utils"
"github.com/spf13/cobra"
"github.com/spf13/viper"
mountUtils "k8s.io/mount-utils"

"github.com/rancher/elemental-cli/cmd/config"
"github.com/rancher/elemental-cli/pkg/action"
elementalError "github.com/rancher/elemental-cli/pkg/error"
"github.com/rancher/elemental-cli/pkg/utils"
)

var outputAllowed = []string{"azure", "gce"}
Expand All @@ -49,7 +51,7 @@ func NewConvertDisk(root *cobra.Command, addCheckRoot bool) *cobra.Command {

cfg, err := config.ReadConfigBuild(viper.GetString("config-dir"), cmd.Flags(), mounter)
if err != nil {
return err
return elementalError.NewFromError(err, elementalError.ReadingBuildConfig)
}

// Set this after parsing of the flags, so it fails on parsing and prints usage properly
Expand All @@ -61,8 +63,9 @@ func NewConvertDisk(root *cobra.Command, addCheckRoot bool) *cobra.Command {
rawDisk := args[0]

if exists, _ := utils.Exists(cfg.Fs, rawDisk); !exists {
cfg.Logger.Errorf("Raw image %s doesnt exist", rawDisk)
return fmt.Errorf("raw image %s doesnt exist", rawDisk)
msg := fmt.Sprintf("Raw image %s doesnt exist", rawDisk)
cfg.Logger.Errorf(msg)
return elementalError.New(msg, elementalError.StatFile)
}

switch imgType {
Expand Down
18 changes: 11 additions & 7 deletions cmd/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ package cmd

import (
"context"
"errors"
"fmt"
"strings"

"github.com/hashicorp/go-getter"
"github.com/rancher/elemental-cli/cmd/config"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/mount-utils"

"github.com/rancher/elemental-cli/cmd/config"
elementalError "github.com/rancher/elemental-cli/pkg/error"
)

func NewDerivativeCmd(root *cobra.Command) *cobra.Command {
Expand All @@ -37,34 +39,36 @@ func NewDerivativeCmd(root *cobra.Command) *cobra.Command {
SilenceErrors: true, // Do not propagate errors down the line, we control them
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), &mount.FakeMounter{})

if err != nil {
cfg.Logger.Errorf("Error reading config: %s\n", err)
return elementalError.NewFromError(err, elementalError.ReadingRunConfig)
}

flavor := args[0]
flavor := strings.ToLower(args[0])
if flavor != "opensuse" && flavor != "ubuntu" && flavor != "fedora" {
cfg.Logger.Errorf("Unsupported flavor")
return errors.New("unsupported flavor")
return elementalError.New("unsupported flavor", elementalError.UnsupportedFlavor)
}

client := &getter.Client{
Ctx: context.Background(),
Dst: fmt.Sprintf("derivatives/%s", flavor),
Dir: true,
Src: "github.com/rancher-sandbox/cOS-toolkit//examples/standard",
Src: "github.com/rancher/elemental-toolkit/examples/standard",
Mode: getter.ClientModeDir,
Detectors: []getter.Detector{
&getter.GitHubDetector{},
},
}

cfg.Logger.Infof("Downloading template...")
err = client.Get()
if err != nil {
cfg.Logger.Errorf("Unable to create derivative")
return err
return elementalError.NewFromError(err, elementalError.DownloadFile)
}

cfg.Logger.Infof("New derivative created successfully")
return nil
},
}
Expand Down
7 changes: 4 additions & 3 deletions cmd/pull-image.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"k8s.io/mount-utils"

"github.com/rancher/elemental-cli/cmd/config"
elementalError "github.com/rancher/elemental-cli/pkg/error"
"github.com/rancher/elemental-cli/pkg/luet"
)

Expand All @@ -41,16 +42,16 @@ func NewPullImageCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command {
},
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), &mount.FakeMounter{})

if err != nil {
cfg.Logger.Errorf("Error reading config: %s\n", err)
return elementalError.NewFromError(err, elementalError.ReadingRunConfig)
}

image := args[0]
destination, err := filepath.Abs(args[1])
if err != nil {
cfg.Logger.Errorf("Invalid path %s", destination)
return err
return elementalError.NewFromError(err, elementalError.StatFile)
}

// Set this after parsing of the flags, so it fails on parsing and prints usage properly
Expand Down Expand Up @@ -82,7 +83,7 @@ func NewPullImageCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command {

if err != nil {
cfg.Logger.Error(err.Error())
return err
return elementalError.NewFromError(err, elementalError.UnpackImage)
}

return nil
Expand Down
6 changes: 4 additions & 2 deletions cmd/run-stage.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"k8s.io/mount-utils"

"github.com/rancher/elemental-cli/cmd/config"
elementalError "github.com/rancher/elemental-cli/pkg/error"
"github.com/rancher/elemental-cli/pkg/utils"
)

Expand All @@ -35,12 +36,13 @@ func NewRunStage(root *cobra.Command) *cobra.Command {
},
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), &mount.FakeMounter{})

if err != nil {
cfg.Logger.Errorf("Error reading config: %s\n", err)
return elementalError.NewFromError(err, elementalError.ReadingRunConfig)
}

return utils.RunStage(&cfg.Config, args[0], cfg.Strict)
err = utils.RunStage(&cfg.Config, args[0], cfg.Strict)
return elementalError.NewFromError(err, elementalError.CloudInitRunStage)
},
}
root.AddCommand(c)
Expand Down
9 changes: 8 additions & 1 deletion docs/elemental_exit-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
| 42 | Error occurred trying to reboot|
| 43 | Error occurred trying to shutdown|
| 44 | Error occurred when labeling partition|
| 44 | Error occurred when unmounting image|
| 45 | Error setting default grub entry|
| 46 | Error occurred during selinux relabeling|
| 47 | Error invalid device specified|
Expand All @@ -58,4 +57,12 @@
| 61 | Error during before-reset hook|
| 62 | Error during after-reset-chroot hook|
| 63 | Error during after-reset hook|
| 64 | Unsupported flavor|
| 65 | Error encountered during cloud-init run-stage|
| 66 | Error unpacking image|
| 67 | Error reading file|
| 68 | No source was provided for the command|
| 69 | Error removing a file|
| 70 | Error calculating checksum|
| 71 | Error occurred when unmounting image|
| 255 | Unknown error|
29 changes: 23 additions & 6 deletions docs/generate_docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ import (
"strconv"
"strings"

"github.com/rancher/elemental-cli/cmd"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"

"github.com/rancher/elemental-cli/cmd"
)

func main() {
Expand All @@ -56,10 +57,14 @@ func main() {
os.Exit(1)
}
}
generateExitCodes()

if err := generateExitCodes(); err != nil {
fmt.Printf("error generating exit-codes: %v\n", err)
os.Exit(1)
}
}

func generateExitCodes() {
func generateExitCodes() error {
fset := token.NewFileSet()
files := []*ast.File{
mustParse(fset, "../pkg/error/exit-codes.go"),
Expand All @@ -68,13 +73,24 @@ func generateExitCodes() {
if err != nil {
panic(err)
}
var exitCodes []*ErrorCode
var (
exitCodes []*ErrorCode
used map[int]bool
)

used = make(map[int]bool)

for _, c := range p.Consts {
// Cast it, its safe as these are constants
v := c.Decl.Specs[0].(*ast.ValueSpec)
val := v.Values[0].(*ast.BasicLit)
code, _ := strconv.Atoi(val.Value)

if _, ok := used[code]; ok {
return fmt.Errorf("duplicate exit-code found: %v", code)
}

used[code] = true
exitCodes = append(exitCodes, &ErrorCode{code: code, doc: c.Doc})
}

Expand All @@ -86,7 +102,7 @@ func generateExitCodes() {

if err != nil {
fmt.Print(err)
return
return err
}

defer func() {
Expand All @@ -99,10 +115,11 @@ func generateExitCodes() {
for _, code := range exitCodes {
_, err = exitCodesFile.WriteString(fmt.Sprintf("| %d | %s|\n", code.code, strings.Replace(code.doc, "\n", "", 1)))
if err != nil {
return
return err
}
}

return nil
}

func mustParse(fset *token.FileSet, filename string) *ast.File {
Expand Down
Loading

0 comments on commit d145f9f

Please sign in to comment.