forked from toolshed/abra
		
	Compare commits
	
		
			21 Commits
		
	
	
		
			0.3.0-alph
			...
			0.3.1-alph
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| fcbf41ee95 | |||
| 5add4ccc1b | |||
| 9220a8c09b | |||
| f78a04109c | |||
| b67ad02f87 | |||
| 215431696e | |||
| cd361237e7 | |||
| db10c7b849 | |||
| d38f82ebe7 | |||
| 59031595ea | |||
| 6f26b51f3e | |||
| 17a5f1529a | |||
| 2ba6445daa | |||
| edb427a7ae | |||
| 3dc186e231 | |||
| 1467ae5007 | |||
| 2b9395be1a | |||
| a539033b55 | |||
| 63d9703d9d | |||
| f9726b6643 | |||
| 4a0761926c | 
| @ -35,3 +35,4 @@ changelog: | ||||
|       - "^style:" | ||||
|       - "^test:" | ||||
|       - "^tests:" | ||||
|       - "^Revert" | ||||
|  | ||||
							
								
								
									
										2
									
								
								Makefile
									
									
									
									
									
								
							
							
						
						
									
										2
									
								
								Makefile
									
									
									
									
									
								
							| @ -32,7 +32,7 @@ static: | ||||
| 	@staticcheck $(ABRA) | ||||
|  | ||||
| test: | ||||
| 	@go test ./... -cover | ||||
| 	@go test ./... -cover -v | ||||
|  | ||||
| loc: | ||||
| 	@find . -name "*.go" | xargs wc -l | ||||
|  | ||||
| @ -18,6 +18,7 @@ to scaling apps up and spinning them down. | ||||
| 	Subcommands: []*cli.Command{ | ||||
| 		appNewCommand, | ||||
| 		appConfigCommand, | ||||
| 		appRestartCommand, | ||||
| 		appDeployCommand, | ||||
| 		appUpgradeCommand, | ||||
| 		appUndeployCommand, | ||||
|  | ||||
| @ -8,6 +8,7 @@ import ( | ||||
| 	abraFormatter "coopcloud.tech/abra/cli/formatter" | ||||
| 	"coopcloud.tech/abra/pkg/catalogue" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"coopcloud.tech/abra/pkg/ssh" | ||||
| 	"coopcloud.tech/tagcmp" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| @ -69,6 +70,12 @@ can take some time. | ||||
| 		} | ||||
| 		sort.Sort(config.ByServerAndType(apps)) | ||||
|  | ||||
| 		for _, app := range apps { | ||||
| 			if err := ssh.EnsureHostKey(app.Server); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		statuses := make(map[string]map[string]string) | ||||
| 		tableCol := []string{"Server", "Type", "Domain"} | ||||
| 		if status { | ||||
|  | ||||
							
								
								
									
										72
									
								
								cli/app/restart.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										72
									
								
								cli/app/restart.go
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,72 @@ | ||||
| package app | ||||
|  | ||||
| import ( | ||||
| 	"errors" | ||||
| 	"fmt" | ||||
| 	"time" | ||||
|  | ||||
| 	"coopcloud.tech/abra/cli/internal" | ||||
| 	"coopcloud.tech/abra/pkg/client" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"github.com/docker/docker/api/types" | ||||
| 	"github.com/docker/docker/api/types/filters" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| ) | ||||
|  | ||||
| var appRestartCommand = &cli.Command{ | ||||
| 	Name:        "restart", | ||||
| 	Usage:       "Restart an app", | ||||
| 	Aliases:     []string{"R"}, | ||||
| 	ArgsUsage:   "<service>", | ||||
| 	Description: `This command restarts a service within a deployed app.`, | ||||
| 	Action: func(c *cli.Context) error { | ||||
| 		app := internal.ValidateApp(c) | ||||
|  | ||||
| 		serviceName := c.Args().Get(1) | ||||
| 		if serviceName == "" { | ||||
| 			err := errors.New("missing service?") | ||||
| 			internal.ShowSubcommandHelpAndError(c, err) | ||||
| 		} | ||||
|  | ||||
| 		cl, err := client.New(app.Server) | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		serviceFilter := fmt.Sprintf("%s_%s", app.StackName(), serviceName) | ||||
| 		filters := filters.NewArgs() | ||||
| 		filters.Add("name", serviceFilter) | ||||
| 		containerOpts := types.ContainerListOptions{Filters: filters} | ||||
| 		containers, err := cl.ContainerList(c.Context, containerOpts) | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
| 		if len(containers) != 1 { | ||||
| 			logrus.Fatalf("expected 1 service but got %v", len(containers)) | ||||
| 		} | ||||
|  | ||||
| 		logrus.Debugf("attempting to restart %s", serviceFilter) | ||||
|  | ||||
| 		timeout := 30 * time.Second | ||||
| 		if err := cl.ContainerRestart(c.Context, containers[0].ID, &timeout); err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		logrus.Infof("%s service restarted", serviceFilter) | ||||
|  | ||||
| 		return nil | ||||
| 	}, | ||||
| 	BashComplete: func(c *cli.Context) { | ||||
| 		appNames, err := config.GetAppNames() | ||||
| 		if err != nil { | ||||
| 			logrus.Warn(err) | ||||
| 		} | ||||
| 		if c.NArg() > 0 { | ||||
| 			return | ||||
| 		} | ||||
| 		for _, a := range appNames { | ||||
| 			fmt.Println(a) | ||||
| 		} | ||||
| 	}, | ||||
| } | ||||
| @ -8,10 +8,13 @@ import ( | ||||
| 	"path" | ||||
|  | ||||
| 	"coopcloud.tech/abra/cli/formatter" | ||||
| 	"coopcloud.tech/abra/cli/internal" | ||||
| 	"coopcloud.tech/abra/pkg/catalogue" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"coopcloud.tech/abra/pkg/git" | ||||
| 	gitPkg "coopcloud.tech/abra/pkg/git" | ||||
| 	"coopcloud.tech/abra/pkg/limit" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	"github.com/go-git/go-git/v5" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| ) | ||||
| @ -48,26 +51,52 @@ var CatalogueSkipList = map[string]bool{ | ||||
| 	"tyop":                  true, | ||||
| } | ||||
|  | ||||
| var commit bool | ||||
| var commitFlag = &cli.BoolFlag{ | ||||
| 	Name:        "commit", | ||||
| 	Usage:       "Commits new generated catalogue changes", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"c"}, | ||||
| 	Destination: &commit, | ||||
| } | ||||
|  | ||||
| var catalogueGenerateCommand = &cli.Command{ | ||||
| 	Name:      "generate", | ||||
| 	Aliases:   []string{"g"}, | ||||
| 	Usage:     "Generate a new copy of the catalogue", | ||||
| 	ArgsUsage: "[<recipe>]", | ||||
| 	BashComplete: func(c *cli.Context) { | ||||
| 		catl, err := catalogue.ReadRecipeCatalogue() | ||||
| 		if err != nil { | ||||
| 			logrus.Warn(err) | ||||
| 		} | ||||
| 		if c.NArg() > 0 { | ||||
| 			return | ||||
| 		} | ||||
| 		for name := range catl { | ||||
| 			fmt.Println(name) | ||||
| 		} | ||||
| 	Name:    "generate", | ||||
| 	Aliases: []string{"g"}, | ||||
| 	Usage:   "Generate a new copy of the catalogue", | ||||
| 	Flags: []cli.Flag{ | ||||
| 		internal.PushFlag, | ||||
| 		commitFlag, | ||||
| 		internal.CommitMessageFlag, | ||||
| 	}, | ||||
| 	Description: ` | ||||
| This command generates a new copy of the recipe catalogue which can be found on: | ||||
|  | ||||
|     https://recipes.coopcloud.tech | ||||
|  | ||||
| It polls the entire git.coopcloud.tech/coop-cloud/... recipe repository | ||||
| listing, parses README and tags to produce recipe metadata and produces a | ||||
| apps.json file which is placed in your ~/.abra/catalogue/recipes.json. | ||||
|  | ||||
| It is possible to generate new metadata for a single recipe by passing | ||||
| <recipe>. The existing local catalogue will be updated, not overwritten. | ||||
|  | ||||
| A new catalogue copy can be published to the recipes repository by passing the | ||||
| "--commit" and "--push" flags. The recipes repository is available here: | ||||
|  | ||||
|     https://git.coopcloud.tech/coop-cloud/recipes | ||||
|  | ||||
| `, | ||||
| 	ArgsUsage: "[<recipe>]", | ||||
| 	Action: func(c *cli.Context) error { | ||||
| 		recipeName := c.Args().First() | ||||
|  | ||||
| 		catalogueDir := path.Join(config.ABRA_DIR, "catalogue") | ||||
| 		url := fmt.Sprintf("%s/%s.git", config.REPOS_BASE_URL, "recipes") | ||||
| 		if err := gitPkg.Clone(catalogueDir, url); err != nil { | ||||
| 			return err | ||||
| 		} | ||||
|  | ||||
| 		repos, err := catalogue.ReadReposMetadata() | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| @ -96,11 +125,11 @@ var catalogueGenerateCommand = &cli.Command{ | ||||
|  | ||||
| 				recipeDir := path.Join(config.ABRA_DIR, "apps", rm.Name) | ||||
|  | ||||
| 				if err := git.Clone(recipeDir, rm.SSHURL); err != nil { | ||||
| 				if err := gitPkg.Clone(recipeDir, rm.SSHURL); err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
|  | ||||
| 				if err := git.EnsureUpToDate(recipeDir); err != nil { | ||||
| 				if err := gitPkg.EnsureUpToDate(recipeDir); err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
|  | ||||
| @ -139,8 +168,8 @@ var catalogueGenerateCommand = &cli.Command{ | ||||
| 				Description:   recipeMeta.Description, | ||||
| 				Website:       recipeMeta.Website, | ||||
| 				Versions:      versions, | ||||
| 				// Category:      ..., // FIXME: once we sort out the machine-readable catalogue interface | ||||
| 				// Features:      ..., // FIXME: once we figure out the machine-readable catalogue interface | ||||
| 				// Category:      ..., // FIXME: parse & load | ||||
| 				// Features:      ..., // FIXME: parse & load | ||||
| 			} | ||||
| 			catlBar.Add(1) | ||||
| 		} | ||||
| @ -172,8 +201,61 @@ var catalogueGenerateCommand = &cli.Command{ | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		logrus.Infof("generated new recipe catalogue in '%s'", config.APPS_JSON) | ||||
| 		cataloguePath := path.Join(config.ABRA_DIR, "catalogue", "recipes.json") | ||||
| 		logrus.Infof("generated new recipe catalogue in %s", cataloguePath) | ||||
|  | ||||
| 		if commit { | ||||
| 			repoPath := path.Join(config.ABRA_DIR, "catalogue") | ||||
| 			commitRepo, err := git.PlainOpen(repoPath) | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
|  | ||||
| 			commitWorktree, err := commitRepo.Worktree() | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
|  | ||||
| 			if internal.CommitMessage == "" { | ||||
| 				prompt := &survey.Input{ | ||||
| 					Message: "commit message", | ||||
| 					Default: "chore: publish new catalogue changes", | ||||
| 				} | ||||
| 				if err := survey.AskOne(prompt, &internal.CommitMessage); err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
| 			} | ||||
|  | ||||
| 			err = commitWorktree.AddGlob("**.json") | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			logrus.Debug("staged **.json for commit") | ||||
|  | ||||
| 			_, err = commitWorktree.Commit(internal.CommitMessage, &git.CommitOptions{}) | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			logrus.Info("changes commited") | ||||
|  | ||||
| 			if err := commitRepo.Push(&git.PushOptions{}); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			logrus.Info("changes pushed") | ||||
| 		} | ||||
|  | ||||
| 		return nil | ||||
| 	}, | ||||
| 	BashComplete: func(c *cli.Context) { | ||||
| 		catl, err := catalogue.ReadRecipeCatalogue() | ||||
| 		if err != nil { | ||||
| 			logrus.Warn(err) | ||||
| 		} | ||||
| 		if c.NArg() > 0 { | ||||
| 			return | ||||
| 		} | ||||
| 		for name := range catl { | ||||
| 			fmt.Println(name) | ||||
| 		} | ||||
| 	}, | ||||
| } | ||||
|  | ||||
| @ -20,6 +20,10 @@ func Truncate(str string) string { | ||||
| 	return fmt.Sprintf(`"%s"`, formatter.Ellipsis(str, 19)) | ||||
| } | ||||
|  | ||||
| func SmallSHA(hash string) string { | ||||
| 	return hash[:8] | ||||
| } | ||||
|  | ||||
| // RemoveSha remove image sha from a string that are added in some docker outputs | ||||
| func RemoveSha(str string) string { | ||||
| 	return strings.Split(str, "@")[0] | ||||
|  | ||||
| @ -8,6 +8,7 @@ import ( | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"coopcloud.tech/abra/pkg/recipe" | ||||
| 	"coopcloud.tech/abra/pkg/secret" | ||||
| 	"coopcloud.tech/abra/pkg/ssh" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| @ -163,6 +164,10 @@ func NewAction(c *cli.Context) error { | ||||
| 	} | ||||
|  | ||||
| 	if Secrets { | ||||
| 		if err := ssh.EnsureHostKey(NewAppServer); err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		secrets, err := createSecrets(sanitisedAppName) | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
|  | ||||
							
								
								
									
										152
									
								
								cli/internal/recipe.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										152
									
								
								cli/internal/recipe.go
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,152 @@ | ||||
| package internal | ||||
|  | ||||
| import ( | ||||
| 	"fmt" | ||||
| 	"strings" | ||||
|  | ||||
| 	"coopcloud.tech/abra/pkg/recipe" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| ) | ||||
|  | ||||
| var Major bool | ||||
| var MajorFlag = &cli.BoolFlag{ | ||||
| 	Name:        "major", | ||||
| 	Usage:       "Increase the major part of the version", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"ma", "x"}, | ||||
| 	Destination: &Major, | ||||
| } | ||||
|  | ||||
| var Minor bool | ||||
| var MinorFlag = &cli.BoolFlag{ | ||||
| 	Name:        "minor", | ||||
| 	Usage:       "Increase the minor part of the version", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"mi", "y"}, | ||||
| 	Destination: &Minor, | ||||
| } | ||||
|  | ||||
| var Patch bool | ||||
| var PatchFlag = &cli.BoolFlag{ | ||||
| 	Name:        "patch", | ||||
| 	Usage:       "Increase the patch part of the version", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"p", "z"}, | ||||
| 	Destination: &Patch, | ||||
| } | ||||
|  | ||||
| var Dry bool | ||||
| var DryFlag = &cli.BoolFlag{ | ||||
| 	Name:        "dry-run", | ||||
| 	Usage:       "No changes are made, only reports changes that would be made", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"d"}, | ||||
| 	Destination: &Dry, | ||||
| } | ||||
|  | ||||
| var Push bool | ||||
| var PushFlag = &cli.BoolFlag{ | ||||
| 	Name:        "push", | ||||
| 	Usage:       "Git push changes", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"P"}, | ||||
| 	Destination: &Push, | ||||
| } | ||||
|  | ||||
| var CommitMessage string | ||||
| var CommitMessageFlag = &cli.StringFlag{ | ||||
| 	Name:        "commit-message", | ||||
| 	Usage:       "Commit message (implies --commit)", | ||||
| 	Aliases:     []string{"cm"}, | ||||
| 	Destination: &CommitMessage, | ||||
| } | ||||
|  | ||||
| var Commit bool | ||||
| var CommitFlag = &cli.BoolFlag{ | ||||
| 	Name:        "commit", | ||||
| 	Usage:       "Commits compose.**yml file changes to recipe repository", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"c"}, | ||||
| 	Destination: &Commit, | ||||
| } | ||||
|  | ||||
| var TagMessage string | ||||
| var TagMessageFlag = &cli.StringFlag{ | ||||
| 	Name:        "tag-comment", | ||||
| 	Usage:       "Description for release tag", | ||||
| 	Aliases:     []string{"t", "tm"}, | ||||
| 	Destination: &TagMessage, | ||||
| } | ||||
|  | ||||
| // PromptBumpType prompts for version bump type | ||||
| func PromptBumpType(tagString string) error { | ||||
| 	if (!Major && !Minor && !Patch) && tagString == "" { | ||||
| 		fmt.Printf(` | ||||
| semver cheat sheet (more via semver.org): | ||||
|   major: new features/bug fixes, backwards incompatible | ||||
|   minor: new features/bug fixes, backwards compatible | ||||
|   patch: bug fixes, backwards compatible | ||||
|  | ||||
| `) | ||||
| 		var chosenBumpType string | ||||
| 		prompt := &survey.Select{ | ||||
| 			Message: fmt.Sprintf("select recipe version increment type"), | ||||
| 			Options: []string{"major", "minor", "patch"}, | ||||
| 		} | ||||
| 		if err := survey.AskOne(prompt, &chosenBumpType); err != nil { | ||||
| 			return err | ||||
| 		} | ||||
| 		SetBumpType(chosenBumpType) | ||||
| 	} | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| // GetBumpType figures out which bump type is specified | ||||
| func GetBumpType() string { | ||||
| 	var bumpType string | ||||
|  | ||||
| 	if Major { | ||||
| 		bumpType = "major" | ||||
| 	} else if Minor { | ||||
| 		bumpType = "minor" | ||||
| 	} else if Patch { | ||||
| 		bumpType = "patch" | ||||
| 	} else { | ||||
| 		logrus.Fatal("no version bump type specififed?") | ||||
| 	} | ||||
|  | ||||
| 	return bumpType | ||||
| } | ||||
|  | ||||
| // SetBumpType figures out which bump type is specified | ||||
| func SetBumpType(bumpType string) { | ||||
| 	if bumpType == "major" { | ||||
| 		Major = true | ||||
| 	} else if bumpType == "minor" { | ||||
| 		Minor = true | ||||
| 	} else if bumpType == "patch" { | ||||
| 		Patch = true | ||||
| 	} else { | ||||
| 		logrus.Fatal("no version bump type specififed?") | ||||
| 	} | ||||
| } | ||||
|  | ||||
| // GetMainApp retrieves the main 'app' image name | ||||
| func GetMainApp(recipe recipe.Recipe) string { | ||||
| 	var app string | ||||
|  | ||||
| 	for _, service := range recipe.Config.Services { | ||||
| 		name := service.Name | ||||
| 		if name == "app" { | ||||
| 			app = strings.Split(service.Image, ":")[0] | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if app == "" { | ||||
| 		logrus.Fatalf("%s has no main 'app' service?", recipe.Name) | ||||
| 	} | ||||
|  | ||||
| 	return app | ||||
| } | ||||
| @ -8,6 +8,7 @@ import ( | ||||
| 	"coopcloud.tech/abra/pkg/catalogue" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"coopcloud.tech/abra/pkg/recipe" | ||||
| 	"coopcloud.tech/abra/pkg/ssh" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| @ -98,6 +99,10 @@ func ValidateApp(c *cli.Context) config.App { | ||||
| 		logrus.Fatal(err) | ||||
| 	} | ||||
|  | ||||
| 	if err := ssh.EnsureHostKey(app.Server); err != nil { | ||||
| 		logrus.Fatal(err) | ||||
| 	} | ||||
|  | ||||
| 	logrus.Debugf("validated '%s' as app argument", appName) | ||||
|  | ||||
| 	return app | ||||
|  | ||||
| @ -63,7 +63,14 @@ var recipeLintCommand = &cli.Command{ | ||||
| 				allImagesTagged = false | ||||
| 			} | ||||
|  | ||||
| 			tag := img.(reference.NamedTagged).Tag() | ||||
| 			var tag string | ||||
| 			switch img.(type) { | ||||
| 			case reference.NamedTagged: | ||||
| 				tag = img.(reference.NamedTagged).Tag() | ||||
| 			case reference.Named: | ||||
| 				noUnstableTags = false | ||||
| 			} | ||||
|  | ||||
| 			if tag == "latest" { | ||||
| 				noUnstableTags = false | ||||
| 			} | ||||
|  | ||||
| @ -4,30 +4,6 @@ import ( | ||||
| 	"github.com/urfave/cli/v2" | ||||
| ) | ||||
|  | ||||
| var Major bool | ||||
| var MajorFlag = &cli.BoolFlag{ | ||||
| 	Name:        "major", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"ma", "x"}, | ||||
| 	Destination: &Major, | ||||
| } | ||||
|  | ||||
| var Minor bool | ||||
| var MinorFlag = &cli.BoolFlag{ | ||||
| 	Name:        "minor", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"mi", "y"}, | ||||
| 	Destination: &Minor, | ||||
| } | ||||
|  | ||||
| var Patch bool | ||||
| var PatchFlag = &cli.BoolFlag{ | ||||
| 	Name:        "patch", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"p", "z"}, | ||||
| 	Destination: &Patch, | ||||
| } | ||||
|  | ||||
| // RecipeCommand defines all recipe related sub-commands. | ||||
| var RecipeCommand = &cli.Command{ | ||||
| 	Name:      "recipe", | ||||
|  | ||||
| @ -6,63 +6,25 @@ import ( | ||||
| 	"strconv" | ||||
| 	"strings" | ||||
|  | ||||
| 	abraFormatter "coopcloud.tech/abra/cli/formatter" | ||||
| 	"coopcloud.tech/abra/cli/internal" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"coopcloud.tech/abra/pkg/recipe" | ||||
| 	recipePkg "coopcloud.tech/abra/pkg/recipe" | ||||
| 	"coopcloud.tech/tagcmp" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	"github.com/docker/distribution/reference" | ||||
| 	"github.com/go-git/go-git/v5" | ||||
| 	"github.com/go-git/go-git/v5/plumbing" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| ) | ||||
|  | ||||
| var Push bool | ||||
| var PushFlag = &cli.BoolFlag{ | ||||
| 	Name:        "push", | ||||
| 	Value:       false, | ||||
| 	Destination: &Push, | ||||
| } | ||||
|  | ||||
| var Dry bool | ||||
| var DryFlag = &cli.BoolFlag{ | ||||
| 	Name:        "dry-run", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"d"}, | ||||
| 	Destination: &Dry, | ||||
| } | ||||
|  | ||||
| var CommitMessage string | ||||
| var CommitMessageFlag = &cli.StringFlag{ | ||||
| 	Name:        "commit-message", | ||||
| 	Usage:       "commit message. Implies --commit", | ||||
| 	Aliases:     []string{"cm"}, | ||||
| 	Destination: &CommitMessage, | ||||
| } | ||||
|  | ||||
| var Commit bool | ||||
| var CommitFlag = &cli.BoolFlag{ | ||||
| 	Name:        "commit", | ||||
| 	Usage:       "add compose.yml to staging area and commit changes", | ||||
| 	Value:       false, | ||||
| 	Aliases:     []string{"c"}, | ||||
| 	Destination: &Commit, | ||||
| } | ||||
|  | ||||
| var TagMessage string | ||||
| var TagMessageFlag = &cli.StringFlag{ | ||||
| 	Name:        "tag-comment", | ||||
| 	Usage:       "tag comment. If not given, user will be asked for it", | ||||
| 	Aliases:     []string{"t", "tm"}, | ||||
| 	Destination: &TagMessage, | ||||
| } | ||||
|  | ||||
| var recipeReleaseCommand = &cli.Command{ | ||||
| 	Name:      "release", | ||||
| 	Usage:     "tag a recipe", | ||||
| 	Usage:     "Release a new recipe version", | ||||
| 	Aliases:   []string{"rl"}, | ||||
| 	ArgsUsage: "<recipe> [<tag>]", | ||||
| 	ArgsUsage: "<recipe> [<version>]", | ||||
| 	Description: ` | ||||
| This command is used to specify a new tag for a recipe. These tags are used to | ||||
| identify different versions of the recipe and are published on the Co-op Cloud | ||||
| @ -83,23 +45,32 @@ updates are properly communicated. | ||||
| Abra does its best to read the "a.b.c" version scheme and communicate what | ||||
| action needs to be taken when performing different operations such as an update | ||||
| or a rollback of an app. | ||||
|  | ||||
| You may invoke this command in "wizard" mode and be prompted for input: | ||||
|  | ||||
|     abra recipe release gitea | ||||
|  | ||||
| `, | ||||
| 	Flags: []cli.Flag{ | ||||
| 		DryFlag, | ||||
| 		PatchFlag, | ||||
| 		MinorFlag, | ||||
| 		MajorFlag, | ||||
| 		PushFlag, | ||||
| 		CommitFlag, | ||||
| 		CommitMessageFlag, | ||||
| 		TagMessageFlag, | ||||
| 		internal.DryFlag, | ||||
| 		internal.MajorFlag, | ||||
| 		internal.MinorFlag, | ||||
| 		internal.PatchFlag, | ||||
| 		internal.PushFlag, | ||||
| 		internal.CommitFlag, | ||||
| 		internal.CommitMessageFlag, | ||||
| 		internal.TagMessageFlag, | ||||
| 	}, | ||||
| 	Action: func(c *cli.Context) error { | ||||
| 		recipe := internal.ValidateRecipe(c) | ||||
| 		recipe := internal.ValidateRecipeWithPrompt(c) | ||||
| 		directory := path.Join(config.APPS_DIR, recipe.Name) | ||||
| 		tagstring := c.Args().Get(1) | ||||
| 		imagesTmp := getImageVersions(recipe) | ||||
| 		mainApp := getMainApp(recipe) | ||||
| 		tagString := c.Args().Get(1) | ||||
| 		mainApp := internal.GetMainApp(recipe) | ||||
|  | ||||
| 		imagesTmp, err := getImageVersions(recipe) | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
| 		mainAppVersion := imagesTmp[mainApp] | ||||
|  | ||||
| 		if err := recipePkg.EnsureExists(recipe.Name); err != nil { | ||||
| @ -107,28 +78,68 @@ or a rollback of an app. | ||||
| 		} | ||||
|  | ||||
| 		if mainAppVersion == "" { | ||||
| 			logrus.Fatal("main app version is empty?") | ||||
| 			logrus.Fatalf("main 'app' service version for %s is empty?", recipe.Name) | ||||
| 		} | ||||
|  | ||||
| 		if tagstring != "" { | ||||
| 			if _, err := tagcmp.Parse(tagstring); err != nil { | ||||
| 		if tagString != "" { | ||||
| 			if _, err := tagcmp.Parse(tagString); err != nil { | ||||
| 				logrus.Fatal("invalid tag specified") | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if TagMessage == "" { | ||||
| 		if (!internal.Major && !internal.Minor && !internal.Patch) && tagString != "" { | ||||
| 			logrus.Fatal("please specify <version> or bump type (--major/--minor/--patch)") | ||||
| 		} | ||||
|  | ||||
| 		if (internal.Major || internal.Minor || internal.Patch) && tagString != "" { | ||||
| 			logrus.Fatal("cannot specify tag and bump type at the same time") | ||||
| 		} | ||||
|  | ||||
| 		// bumpType is used to decide what part of the tag should be incremented | ||||
| 		bumpType := btoi(internal.Major)*4 + btoi(internal.Minor)*2 + btoi(internal.Patch) | ||||
| 		if bumpType != 0 { | ||||
| 			// a bitwise check if the number is a power of 2 | ||||
| 			if (bumpType & (bumpType - 1)) != 0 { | ||||
| 				logrus.Fatal("you can only use one of: --major, --minor, --patch.") | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if err := internal.PromptBumpType(tagString); err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		if internal.TagMessage == "" { | ||||
| 			prompt := &survey.Input{ | ||||
| 				Message: "tag message", | ||||
| 				Default: fmt.Sprintf("chore: publish new %s version", internal.GetBumpType()), | ||||
| 			} | ||||
| 			if err := survey.AskOne(prompt, &TagMessage); err != nil { | ||||
| 			if err := survey.AskOne(prompt, &internal.TagMessage); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		var createTagOptions git.CreateTagOptions | ||||
| 		createTagOptions.Message = TagMessage | ||||
| 		createTagOptions.Message = internal.TagMessage | ||||
|  | ||||
| 		if Commit || (CommitMessage != "") { | ||||
| 		if !internal.Commit { | ||||
| 			prompt := &survey.Confirm{ | ||||
| 				Message: "git commit changes also?", | ||||
| 			} | ||||
| 			if err := survey.AskOne(prompt, &internal.Commit); err != nil { | ||||
| 				return err | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if !internal.Push { | ||||
| 			prompt := &survey.Confirm{ | ||||
| 				Message: "git push changes also?", | ||||
| 			} | ||||
| 			if err := survey.AskOne(prompt, &internal.Push); err != nil { | ||||
| 				return err | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if internal.Commit || internal.CommitMessage != "" { | ||||
| 			commitRepo, err := git.PlainOpen(directory) | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| @ -138,25 +149,31 @@ or a rollback of an app. | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
|  | ||||
| 			if CommitMessage == "" { | ||||
| 			if internal.CommitMessage == "" { | ||||
| 				prompt := &survey.Input{ | ||||
| 					Message: "commit message", | ||||
| 					Default: fmt.Sprintf("chore: publish new %s version", internal.GetBumpType()), | ||||
| 				} | ||||
| 				if err := survey.AskOne(prompt, &CommitMessage); err != nil { | ||||
| 				if err := survey.AskOne(prompt, &internal.CommitMessage); err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
| 			} | ||||
|  | ||||
| 			err = commitWorktree.AddGlob("compose.**yml") | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			logrus.Debug("staged compose.**yml for commit") | ||||
|  | ||||
| 			_, err = commitWorktree.Commit(CommitMessage, &git.CommitOptions{}) | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			if !internal.Dry { | ||||
| 				_, err = commitWorktree.Commit(internal.CommitMessage, &git.CommitOptions{}) | ||||
| 				if err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
| 				logrus.Info("changes commited") | ||||
| 			} else { | ||||
| 				logrus.Info("dry run only: NOT committing changes") | ||||
| 			} | ||||
| 			logrus.Info("changes commited") | ||||
| 		} | ||||
|  | ||||
| 		repo, err := git.PlainOpen(directory) | ||||
| @ -168,20 +185,8 @@ or a rollback of an app. | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		// bumpType is used to decide what part of the tag should be incremented | ||||
| 		bumpType := btoi(Major)*4 + btoi(Minor)*2 + btoi(Patch) | ||||
| 		if bumpType != 0 { | ||||
| 			// a bitwise check if the number is a power of 2 | ||||
| 			if (bumpType & (bumpType - 1)) != 0 { | ||||
| 				logrus.Fatal("you can only use one of: --major, --minor, --patch.") | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if tagstring != "" { | ||||
| 			if bumpType > 0 { | ||||
| 				logrus.Warn("user specified a version number and --major/--minor/--patch at the same time! using version number...") | ||||
| 			} | ||||
| 			tag, err := tagcmp.Parse(tagstring) | ||||
| 		if tagString != "" { | ||||
| 			tag, err := tagcmp.Parse(tagString) | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| @ -193,19 +198,23 @@ or a rollback of an app. | ||||
| 				tag.Patch = "0" | ||||
| 				tag.MissingPatch = false | ||||
| 			} | ||||
| 			tagstring = fmt.Sprintf("%s+%s", tag.String(), mainAppVersion) | ||||
| 			if Dry { | ||||
| 				logrus.Info(fmt.Sprintf("dry run only: NOT creating tag %s at %s", tagstring, head.Hash())) | ||||
| 			tagString = fmt.Sprintf("%s+%s", tag.String(), mainAppVersion) | ||||
| 			if internal.Dry { | ||||
| 				hash := abraFormatter.SmallSHA(head.Hash().String()) | ||||
| 				logrus.Info(fmt.Sprintf("dry run only: NOT creating tag %s at %s", tagString, hash)) | ||||
| 				return nil | ||||
| 			} | ||||
|  | ||||
| 			repo.CreateTag(tagstring, head.Hash(), &createTagOptions) | ||||
| 			logrus.Info(fmt.Sprintf("created tag %s at %s", tagstring, head.Hash())) | ||||
| 			if Push { | ||||
| 			repo.CreateTag(tagString, head.Hash(), &createTagOptions) | ||||
| 			hash := abraFormatter.SmallSHA(head.Hash().String()) | ||||
| 			logrus.Info(fmt.Sprintf("created tag %s at %s", tagString, hash)) | ||||
| 			if internal.Push && !internal.Dry { | ||||
| 				if err := repo.Push(&git.PushOptions{}); err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
| 				logrus.Info(fmt.Sprintf("pushed tag %s to remote", tagstring)) | ||||
| 				logrus.Info(fmt.Sprintf("pushed tag %s to remote", tagString)) | ||||
| 			} else { | ||||
| 				logrus.Info("dry run only: NOT pushing changes") | ||||
| 			} | ||||
|  | ||||
| 			return nil | ||||
| @ -236,25 +245,23 @@ or a rollback of an app. | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		fmt.Println(lastGitTag) | ||||
|  | ||||
| 		newTag := lastGitTag | ||||
| 		var newTagString string | ||||
| 		var newtagString string | ||||
| 		if bumpType > 0 { | ||||
| 			if Patch { | ||||
| 			if internal.Patch { | ||||
| 				now, err := strconv.Atoi(newTag.Patch) | ||||
| 				if err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
| 				newTag.Patch = strconv.Itoa(now + 1) | ||||
| 			} else if Minor { | ||||
| 			} else if internal.Minor { | ||||
| 				now, err := strconv.Atoi(newTag.Minor) | ||||
| 				if err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| 				} | ||||
| 				newTag.Patch = "0" | ||||
| 				newTag.Minor = strconv.Itoa(now + 1) | ||||
| 			} else if Major { | ||||
| 			} else if internal.Major { | ||||
| 				now, err := strconv.Atoi(newTag.Major) | ||||
| 				if err != nil { | ||||
| 					logrus.Fatal(err) | ||||
| @ -263,57 +270,70 @@ or a rollback of an app. | ||||
| 				newTag.Minor = "0" | ||||
| 				newTag.Major = strconv.Itoa(now + 1) | ||||
| 			} | ||||
| 		} else { | ||||
| 			logrus.Fatal("we don't support automatic tag generation yet - specify a version or use one of: --major --minor --patch") | ||||
| 		} | ||||
|  | ||||
| 		newTag.Metadata = mainAppVersion | ||||
| 		newTagString = newTag.String() | ||||
| 		if Dry { | ||||
| 			logrus.Info(fmt.Sprintf("dry run only: NOT creating tag %s at %s", newTagString, head.Hash())) | ||||
| 		newtagString = newTag.String() | ||||
| 		if internal.Dry { | ||||
| 			hash := abraFormatter.SmallSHA(head.Hash().String()) | ||||
| 			logrus.Info(fmt.Sprintf("dry run only: NOT creating tag %s at %s", newtagString, hash)) | ||||
| 			return nil | ||||
| 		} | ||||
|  | ||||
| 		repo.CreateTag(newTagString, head.Hash(), &createTagOptions) | ||||
| 		logrus.Info(fmt.Sprintf("created tag %s at %s", newTagString, head.Hash())) | ||||
| 		if Push { | ||||
| 		repo.CreateTag(newtagString, head.Hash(), &createTagOptions) | ||||
| 		hash := abraFormatter.SmallSHA(head.Hash().String()) | ||||
| 		logrus.Info(fmt.Sprintf("created tag %s at %s", newtagString, hash)) | ||||
| 		if internal.Push && !internal.Dry { | ||||
| 			if err := repo.Push(&git.PushOptions{}); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			logrus.Info(fmt.Sprintf("pushed tag %s to remote", newTagString)) | ||||
| 			logrus.Info(fmt.Sprintf("pushed tag %s to remote", newtagString)) | ||||
| 		} else { | ||||
| 			logrus.Info("gry run only: NOT pushing changes") | ||||
| 		} | ||||
|  | ||||
| 		return nil | ||||
|  | ||||
| 	}, | ||||
| } | ||||
|  | ||||
| func getImageVersions(recipe recipe.Recipe) map[string]string { | ||||
|  | ||||
| // getImageVersions retrieves image versions for a recipe | ||||
| func getImageVersions(recipe recipe.Recipe) (map[string]string, error) { | ||||
| 	var services = make(map[string]string) | ||||
|  | ||||
| 	for _, service := range recipe.Config.Services { | ||||
| 		if service.Image == "" { | ||||
| 			continue | ||||
| 		} | ||||
| 		srv := strings.Split(service.Image, ":") | ||||
| 		services[srv[0]] = srv[1] | ||||
| 	} | ||||
|  | ||||
| 	return services | ||||
| } | ||||
|  | ||||
| func getMainApp(recipe recipe.Recipe) string { | ||||
| 	for _, service := range recipe.Config.Services { | ||||
| 		name := service.Name | ||||
| 		if name == "app" { | ||||
| 			return strings.Split(service.Image, ":")[0] | ||||
| 		img, err := reference.ParseNormalizedNamed(service.Image) | ||||
| 		if err != nil { | ||||
| 			return services, err | ||||
| 		} | ||||
|  | ||||
| 		path := reference.Path(img) | ||||
| 		if strings.Contains(path, "library") { | ||||
| 			path = strings.Split(path, "/")[1] | ||||
| 		} | ||||
|  | ||||
| 		var tag string | ||||
| 		switch img.(type) { | ||||
| 		case reference.NamedTagged: | ||||
| 			tag = img.(reference.NamedTagged).Tag() | ||||
| 		case reference.Named: | ||||
| 			logrus.Fatalf("%s service is missing image tag?", path) | ||||
| 		} | ||||
|  | ||||
| 		services[path] = tag | ||||
| 	} | ||||
| 	return "" | ||||
|  | ||||
| 	return services, nil | ||||
| } | ||||
|  | ||||
| // btoi converts a boolean value into an integer | ||||
| func btoi(b bool) int { | ||||
| 	if b { | ||||
| 		return 1 | ||||
| 	} | ||||
|  | ||||
| 	return 0 | ||||
| } | ||||
|  | ||||
| @ -1,12 +1,17 @@ | ||||
| package recipe | ||||
|  | ||||
| import ( | ||||
| 	"errors" | ||||
| 	"fmt" | ||||
| 	"path" | ||||
| 	"strconv" | ||||
|  | ||||
| 	"coopcloud.tech/abra/cli/internal" | ||||
| 	"coopcloud.tech/abra/pkg/catalogue" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"coopcloud.tech/tagcmp" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	"github.com/go-git/go-git/v5" | ||||
| 	"github.com/go-git/go-git/v5/plumbing" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| ) | ||||
| @ -15,18 +20,167 @@ var recipeSyncCommand = &cli.Command{ | ||||
| 	Name:      "sync", | ||||
| 	Usage:     "Ensure recipe version labels are up-to-date", | ||||
| 	Aliases:   []string{"s"}, | ||||
| 	ArgsUsage: "<recipe> <version>", | ||||
| 	ArgsUsage: "<recipe> [<version>]", | ||||
| 	Flags: []cli.Flag{ | ||||
| 		internal.DryFlag, | ||||
| 		internal.MajorFlag, | ||||
| 		internal.MinorFlag, | ||||
| 		internal.PatchFlag, | ||||
| 	}, | ||||
| 	Description: ` | ||||
| This command will generate labels for the main recipe service (i.e. by | ||||
| convention, typically the service named "app") which corresponds to the | ||||
| following format: | ||||
| convention, the service named "app") which corresponds to the following format: | ||||
|  | ||||
|     coop-cloud.${STACK_NAME}.version=<version> | ||||
|  | ||||
| The <version> is determined by the recipe maintainer and is specified on the | ||||
| command-line. The <recipe> configuration will be updated on the local file | ||||
| system. | ||||
|  | ||||
| You may invoke this command in "wizard" mode and be prompted for input: | ||||
|  | ||||
|     abra recipe sync | ||||
|  | ||||
| `, | ||||
| 	Action: func(c *cli.Context) error { | ||||
| 		recipe := internal.ValidateRecipeWithPrompt(c) | ||||
|  | ||||
| 		mainApp := internal.GetMainApp(recipe) | ||||
|  | ||||
| 		imagesTmp, err := getImageVersions(recipe) | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
| 		mainAppVersion := imagesTmp[mainApp] | ||||
|  | ||||
| 		tags, err := recipe.Tags() | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		nextTag := c.Args().Get(1) | ||||
| 		if len(tags) == 0 && nextTag == "" { | ||||
| 			logrus.Warnf("no tags found for %s", recipe.Name) | ||||
| 			var chosenVersion string | ||||
| 			edPrompt := &survey.Select{ | ||||
| 				Message: "which version do you want to begin with?", | ||||
| 				Options: []string{"0.1.0", "1.0.0"}, | ||||
| 			} | ||||
| 			if err := survey.AskOne(edPrompt, &chosenVersion); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			nextTag = fmt.Sprintf("%s+%s", chosenVersion, mainAppVersion) | ||||
| 		} | ||||
|  | ||||
| 		if nextTag == "" && (!internal.Major && !internal.Minor && !internal.Patch) { | ||||
| 			if err := internal.PromptBumpType(""); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if nextTag == "" { | ||||
| 			recipeDir := path.Join(config.APPS_DIR, recipe.Name) | ||||
| 			repo, err := git.PlainOpen(recipeDir) | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			var lastGitTag tagcmp.Tag | ||||
| 			iter, err := repo.Tags() | ||||
| 			if err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			if err := iter.ForEach(func(ref *plumbing.Reference) error { | ||||
| 				obj, err := repo.TagObject(ref.Hash()) | ||||
| 				if err != nil { | ||||
| 					return err | ||||
| 				} | ||||
| 				tagcmpTag, err := tagcmp.Parse(obj.Name) | ||||
| 				if err != nil { | ||||
| 					return err | ||||
| 				} | ||||
| 				if (lastGitTag == tagcmp.Tag{}) { | ||||
| 					lastGitTag = tagcmpTag | ||||
| 				} else if tagcmpTag.IsGreaterThan(lastGitTag) { | ||||
| 					lastGitTag = tagcmpTag | ||||
| 				} | ||||
| 				return nil | ||||
| 			}); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
|  | ||||
| 			// bumpType is used to decide what part of the tag should be incremented | ||||
| 			bumpType := btoi(internal.Major)*4 + btoi(internal.Minor)*2 + btoi(internal.Patch) | ||||
| 			if bumpType != 0 { | ||||
| 				// a bitwise check if the number is a power of 2 | ||||
| 				if (bumpType & (bumpType - 1)) != 0 { | ||||
| 					logrus.Fatal("you can only use one of: --major, --minor, --patch.") | ||||
| 				} | ||||
| 			} | ||||
|  | ||||
| 			newTag := lastGitTag | ||||
| 			if bumpType > 0 { | ||||
| 				if internal.Patch { | ||||
| 					now, err := strconv.Atoi(newTag.Patch) | ||||
| 					if err != nil { | ||||
| 						logrus.Fatal(err) | ||||
| 					} | ||||
| 					newTag.Patch = strconv.Itoa(now + 1) | ||||
| 				} else if internal.Minor { | ||||
| 					now, err := strconv.Atoi(newTag.Minor) | ||||
| 					if err != nil { | ||||
| 						logrus.Fatal(err) | ||||
| 					} | ||||
| 					newTag.Patch = "0" | ||||
| 					newTag.Minor = strconv.Itoa(now + 1) | ||||
| 				} else if internal.Major { | ||||
| 					now, err := strconv.Atoi(newTag.Major) | ||||
| 					if err != nil { | ||||
| 						logrus.Fatal(err) | ||||
| 					} | ||||
| 					newTag.Patch = "0" | ||||
| 					newTag.Minor = "0" | ||||
| 					newTag.Major = strconv.Itoa(now + 1) | ||||
| 				} | ||||
| 			} | ||||
|  | ||||
| 			newTag.Metadata = mainAppVersion | ||||
| 			logrus.Debugf("choosing %s as new version for %s", newTag.String(), recipe.Name) | ||||
| 			nextTag = newTag.String() | ||||
| 		} | ||||
|  | ||||
| 		if _, err := tagcmp.Parse(nextTag); err != nil { | ||||
| 			logrus.Fatalf("invalid version %s specified", nextTag) | ||||
| 		} | ||||
|  | ||||
| 		mainService := "app" | ||||
| 		var services []string | ||||
| 		hasAppService := false | ||||
| 		for _, service := range recipe.Config.Services { | ||||
| 			services = append(services, service.Name) | ||||
| 			if service.Name == "app" { | ||||
| 				hasAppService = true | ||||
| 				logrus.Debugf("detected app service in %s", recipe.Name) | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if !hasAppService { | ||||
| 			logrus.Fatalf("%s has no main 'app' service?", recipe.Name) | ||||
| 		} | ||||
|  | ||||
| 		logrus.Debugf("selecting %s as the service to sync version label", mainService) | ||||
|  | ||||
| 		label := fmt.Sprintf("coop-cloud.${STACK_NAME}.version=%s", nextTag) | ||||
| 		if !internal.Dry { | ||||
| 			if err := recipe.UpdateLabel(mainService, label); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			logrus.Infof("synced label '%s' to service '%s'", label, mainService) | ||||
| 		} else { | ||||
| 			logrus.Infof("dry run only: NOT syncing label %s for recipe %s", nextTag, recipe.Name) | ||||
| 		} | ||||
|  | ||||
| 		return nil | ||||
| 	}, | ||||
| 	BashComplete: func(c *cli.Context) { | ||||
| 		catl, err := catalogue.ReadRecipeCatalogue() | ||||
| 		if err != nil { | ||||
| @ -39,50 +193,4 @@ system. | ||||
| 			fmt.Println(name) | ||||
| 		} | ||||
| 	}, | ||||
| 	Action: func(c *cli.Context) error { | ||||
| 		if c.Args().Len() != 2 { | ||||
| 			internal.ShowSubcommandHelpAndError(c, errors.New("missing <recipe>/<version> arguments?")) | ||||
| 		} | ||||
|  | ||||
| 		recipe := internal.ValidateRecipe(c) | ||||
|  | ||||
| 		// TODO: validate with tagcmp when new commits come in | ||||
| 		// See https://git.coopcloud.tech/coop-cloud/abra/pulls/109 | ||||
| 		nextTag := c.Args().Get(1) | ||||
|  | ||||
| 		mainService := "app" | ||||
| 		var services []string | ||||
| 		hasAppService := false | ||||
| 		for _, service := range recipe.Config.Services { | ||||
| 			services = append(services, service.Name) | ||||
| 			if service.Name == "app" { | ||||
| 				hasAppService = true | ||||
| 				logrus.Debugf("detected app service in '%s'", recipe.Name) | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if !hasAppService { | ||||
| 			logrus.Warnf("no 'app' service defined in '%s'", recipe.Name) | ||||
| 			var chosenService string | ||||
| 			prompt := &survey.Select{ | ||||
| 				Message: fmt.Sprintf("what is the main service name for '%s'?", recipe.Name), | ||||
| 				Options: services, | ||||
| 			} | ||||
| 			if err := survey.AskOne(prompt, &chosenService); err != nil { | ||||
| 				logrus.Fatal(err) | ||||
| 			} | ||||
| 			mainService = chosenService | ||||
| 		} | ||||
|  | ||||
| 		logrus.Debugf("selecting '%s' as the service to sync version labels", mainService) | ||||
|  | ||||
| 		label := fmt.Sprintf("coop-cloud.${STACK_NAME}.version=%s", nextTag) | ||||
| 		if err := recipe.UpdateLabel(mainService, label); err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| 		} | ||||
|  | ||||
| 		logrus.Infof("synced label '%s' to service '%s'", label, mainService) | ||||
|  | ||||
| 		return nil | ||||
| 	}, | ||||
| } | ||||
|  | ||||
| @ -36,17 +36,22 @@ update the relevant compose file tags on the local file system. | ||||
| Some image tags cannot be parsed because they do not follow some sort of | ||||
| semver-like convention. In this case, all possible tags will be listed and it | ||||
| is up to the end-user to decide. | ||||
|  | ||||
| You may invoke this command in "wizard" mode and be prompted for input: | ||||
|  | ||||
|     abra recipe upgrade | ||||
|  | ||||
| `, | ||||
| 	ArgsUsage: "<recipe>", | ||||
| 	Flags: []cli.Flag{ | ||||
| 		PatchFlag, | ||||
| 		MinorFlag, | ||||
| 		MajorFlag, | ||||
| 		internal.PatchFlag, | ||||
| 		internal.MinorFlag, | ||||
| 		internal.MajorFlag, | ||||
| 	}, | ||||
| 	Action: func(c *cli.Context) error { | ||||
| 		recipe := internal.ValidateRecipe(c) | ||||
| 		recipe := internal.ValidateRecipeWithPrompt(c) | ||||
|  | ||||
| 		bumpType := btoi(Major)*4 + btoi(Minor)*2 + btoi(Patch) | ||||
| 		bumpType := btoi(internal.Major)*4 + btoi(internal.Minor)*2 + btoi(internal.Patch) | ||||
| 		if bumpType != 0 { | ||||
| 			// a bitwise check if the number is a power of 2 | ||||
| 			if (bumpType & (bumpType - 1)) != 0 { | ||||
| @ -179,11 +184,11 @@ is up to the end-user to decide. | ||||
| 					if contains { | ||||
| 						logrus.Infof("Upgrading service %s from %s to %s (pinned tag: %s)", service.Name, tag.String(), upgradeTag, pinnedTagString) | ||||
| 					} else { | ||||
| 						logrus.Infof("service %s, image %s pinned to %s. No compatible upgrade found", service.Name, servicePins[service.Name].image, pinnedTagString) | ||||
| 						logrus.Infof("service %s, image %s pinned to %s, no compatible upgrade found", service.Name, servicePins[service.Name].image, pinnedTagString) | ||||
| 						continue | ||||
| 					} | ||||
| 				} else { | ||||
| 					logrus.Fatalf("Service %s is at version %s, but pinned to %s. Please correct your compose.yml file manually!", service.Name, tag.String(), pinnedTag.String()) | ||||
| 					logrus.Fatalf("Service %s is at version %s, but pinned to %s, please correct your compose.yml file manually!", service.Name, tag.String(), pinnedTag.String()) | ||||
| 					continue | ||||
| 				} | ||||
| 			} else { | ||||
|  | ||||
| @ -17,13 +17,13 @@ import ( | ||||
| 	"coopcloud.tech/abra/cli/internal" | ||||
| 	"coopcloud.tech/abra/pkg/client" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	contextPkg "coopcloud.tech/abra/pkg/context" | ||||
| 	"coopcloud.tech/abra/pkg/server" | ||||
| 	"coopcloud.tech/abra/pkg/ssh" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	"github.com/docker/docker/api/types" | ||||
| 	"github.com/docker/docker/api/types/swarm" | ||||
| 	dockerClient "github.com/docker/docker/client" | ||||
| 	"github.com/sfreiberg/simplessh" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| ) | ||||
| @ -166,7 +166,7 @@ func newLocalServer(c *cli.Context, domainName string) error { | ||||
| } | ||||
|  | ||||
| func newContext(c *cli.Context, domainName, username, port string) error { | ||||
| 	store := client.NewDefaultDockerContextStore() | ||||
| 	store := contextPkg.NewDefaultDockerContextStore() | ||||
| 	contexts, err := store.Store.List() | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| @ -196,7 +196,7 @@ func newClient(c *cli.Context, domainName string) (*dockerClient.Client, error) | ||||
| 	return cl, nil | ||||
| } | ||||
|  | ||||
| func installDocker(c *cli.Context, cl *dockerClient.Client, sshCl *simplessh.Client, domainName string) error { | ||||
| func installDocker(c *cli.Context, cl *dockerClient.Client, sshCl *ssh.Client, domainName string) error { | ||||
| 	result, err := sshCl.Exec("which docker") | ||||
| 	if err != nil && string(result) != "" { | ||||
| 		return err | ||||
|  | ||||
| @ -4,8 +4,8 @@ import ( | ||||
| 	"strings" | ||||
|  | ||||
| 	"coopcloud.tech/abra/cli/formatter" | ||||
| 	"coopcloud.tech/abra/pkg/client" | ||||
| 	"coopcloud.tech/abra/pkg/config" | ||||
| 	"coopcloud.tech/abra/pkg/context" | ||||
| 	"github.com/docker/cli/cli/connhelper/ssh" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"github.com/urfave/cli/v2" | ||||
| @ -18,7 +18,7 @@ var serverListCommand = &cli.Command{ | ||||
| 	ArgsUsage: " ", | ||||
| 	HideHelp:  true, | ||||
| 	Action: func(c *cli.Context) error { | ||||
| 		dockerContextStore := client.NewDefaultDockerContextStore() | ||||
| 		dockerContextStore := context.NewDefaultDockerContextStore() | ||||
| 		contexts, err := dockerContextStore.Store.List() | ||||
| 		if err != nil { | ||||
| 			logrus.Fatal(err) | ||||
| @ -36,7 +36,7 @@ var serverListCommand = &cli.Command{ | ||||
| 		for _, serverName := range serverNames { | ||||
| 			var row []string | ||||
| 			for _, ctx := range contexts { | ||||
| 				endpoint, err := client.GetContextEndpoint(ctx) | ||||
| 				endpoint, err := context.GetContextEndpoint(ctx) | ||||
| 				if err != nil && strings.Contains(err.Error(), "does not exist") { | ||||
| 					// No local context found, we can continue safely | ||||
| 					continue | ||||
|  | ||||
							
								
								
									
										5
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										5
									
								
								go.mod
									
									
									
									
									
								
							| @ -28,10 +28,10 @@ require ( | ||||
| 	coopcloud.tech/libcapsul v0.0.0-20211022074848-c35e78fe3f3e | ||||
| 	github.com/Microsoft/hcsshim v0.8.21 // indirect | ||||
| 	github.com/containerd/containerd v1.5.5 // indirect | ||||
| 	github.com/davidmz/go-pageant v1.0.2 // indirect | ||||
| 	github.com/docker/docker-credential-helpers v0.6.4 // indirect | ||||
| 	github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect | ||||
| 	github.com/fvbommel/sortorder v1.0.2 // indirect | ||||
| 	github.com/gliderlabs/ssh v0.2.2 | ||||
| 	github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect | ||||
| 	github.com/gorilla/mux v1.8.0 // indirect | ||||
| 	github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 | ||||
| @ -40,9 +40,8 @@ require ( | ||||
| 	github.com/moby/sys/mount v0.2.0 // indirect | ||||
| 	github.com/morikuni/aec v1.0.0 // indirect | ||||
| 	github.com/opencontainers/runc v1.0.2 // indirect | ||||
| 	github.com/pkg/sftp v1.13.4 // indirect | ||||
| 	github.com/sfreiberg/simplessh v0.0.0-20180301191542-495cbb862a9c | ||||
| 	github.com/theupdateframework/notary v0.7.0 // indirect | ||||
| 	github.com/xeipuuv/gojsonschema v1.2.0 // indirect | ||||
| 	golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 | ||||
| 	golang.org/x/sys v0.0.0-20210910150752-751e447fb3d0 | ||||
| ) | ||||
|  | ||||
							
								
								
									
										11
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										11
									
								
								go.sum
									
									
									
									
									
								
							| @ -253,8 +253,6 @@ github.com/danieljoos/wincred v1.1.0/go.mod h1:XYlo+eRTsVA9aHGp7NGjFkPla4m+DCL7h | ||||
| github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||||
| github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= | ||||
| github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||||
| github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0= | ||||
| github.com/davidmz/go-pageant v1.0.2/go.mod h1:P2EDDnMqIwG5Rrp05dTRITj9z2zpGcD9efWSkTNKLIE= | ||||
| github.com/denisenkom/go-mssqldb v0.0.0-20191128021309-1d7a30a10f73/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= | ||||
| github.com/denverdino/aliyungo v0.0.0-20190125010748-a747050bb1ba/go.mod h1:dV8lFg6daOBZbT6/BDGIz6Y3WFGn8juu6G+CQ6LHtl0= | ||||
| github.com/dgrijalva/jwt-go v0.0.0-20170104182250-a601269ab70c/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= | ||||
| @ -304,6 +302,7 @@ github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLi | ||||
| github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 h1:JWuenKqqX8nojtoVVWjGfOF9635RETekkoH6Cc9SX0A= | ||||
| github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqLaRiH3MsBH8va0n7s1pQYcu3uTb8G4tygF4Zg= | ||||
| github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= | ||||
| github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ= | ||||
| github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= | ||||
| github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= | ||||
| github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= | ||||
| @ -501,8 +500,6 @@ github.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdY | ||||
| github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= | ||||
| github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= | ||||
| github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= | ||||
| github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= | ||||
| github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= | ||||
| github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= | ||||
| github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= | ||||
| github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= | ||||
| @ -643,8 +640,6 @@ github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV | ||||
| github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= | ||||
| github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= | ||||
| github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= | ||||
| github.com/pkg/sftp v1.13.4 h1:Lb0RYJCmgUcBgZosfoi9Y9sbl6+LJgOIgk/2Y4YjMFg= | ||||
| github.com/pkg/sftp v1.13.4/go.mod h1:LzqnAvaD5TWeNBsZpfKxSYn1MbjWwOsCIAFFJbpIsK8= | ||||
| github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= | ||||
| github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||||
| github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= | ||||
| @ -699,8 +694,6 @@ github.com/schultz-is/passgen v1.0.1/go.mod h1:NnqzT2aSfvyheNQvBtlLUa0YlPFLDj60J | ||||
| github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= | ||||
| github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= | ||||
| github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= | ||||
| github.com/sfreiberg/simplessh v0.0.0-20180301191542-495cbb862a9c h1:7Q+2oF0uBoLEV+j13E3/xUkPkI7f+sFNPZOPo2jmrWk= | ||||
| github.com/sfreiberg/simplessh v0.0.0-20180301191542-495cbb862a9c/go.mod h1:sB7d6wQapoRM+qx5MgQYB6JVHtel4YHRr0NXXCkXiwQ= | ||||
| github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= | ||||
| github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= | ||||
| github.com/sirupsen/logrus v1.0.4-0.20170822132746-89742aefa4b2/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= | ||||
| @ -827,7 +820,6 @@ golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPh | ||||
| golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= | ||||
| golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= | ||||
| golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= | ||||
| golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= | ||||
| golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= | ||||
| golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= | ||||
| golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= | ||||
| @ -974,7 +966,6 @@ golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7w | ||||
| golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||||
| golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||||
| golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||||
| golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||||
| golang.org/x/sys v0.0.0-20210426230700-d19ff857e887/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||||
| golang.org/x/sys v0.0.0-20210502180810-71e4cd670f79/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||||
| golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||||
|  | ||||
| @ -6,6 +6,7 @@ import ( | ||||
| 	"os" | ||||
| 	"time" | ||||
|  | ||||
| 	contextPkg "coopcloud.tech/abra/pkg/context" | ||||
| 	commandconnPkg "coopcloud.tech/abra/pkg/upstream/commandconn" | ||||
| 	"github.com/docker/docker/client" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| @ -21,7 +22,7 @@ func New(contextName string) (*client.Client, error) { | ||||
| 			return nil, err | ||||
| 		} | ||||
|  | ||||
| 		ctxEndpoint, err := GetContextEndpoint(context) | ||||
| 		ctxEndpoint, err := contextPkg.GetContextEndpoint(context) | ||||
| 		if err != nil { | ||||
| 			return nil, err | ||||
| 		} | ||||
|  | ||||
| @ -1,46 +0,0 @@ | ||||
| package client_test | ||||
|  | ||||
| import ( | ||||
| 	"fmt" | ||||
| 	"testing" | ||||
|  | ||||
| 	"coopcloud.tech/abra/pkg/client" | ||||
| ) | ||||
|  | ||||
| // use at the start to ensure testContext[0, 1, ..., amnt-1] exist and | ||||
| // testContextFail[0, 1, ..., failAmnt-1] don't exist | ||||
| func ensureTestState(amnt, failAmnt int) error { | ||||
| 	for i := 0; i < amnt; i++ { | ||||
| 		err := client.CreateContext(fmt.Sprintf("testContext%d", i), "", "") | ||||
| 		if err != nil { | ||||
| 			return err | ||||
| 		} | ||||
| 	} | ||||
| 	for i := 0; i < failAmnt; i++ { | ||||
| 		if _, er := client.GetContext(fmt.Sprintf("testContextFail%d", i)); er == nil { | ||||
| 			err := client.DeleteContext(fmt.Sprintf("testContextFail%d", i)) | ||||
| 			if err != nil { | ||||
| 				return err | ||||
| 			} | ||||
| 		} | ||||
| 	} | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| func TestNew(t *testing.T) { | ||||
| 	err := ensureTestState(1, 1) | ||||
| 	if err != nil { | ||||
| 		t.Errorf("Couldn't ensure existence/nonexistence of contexts: %s", err) | ||||
| 	} | ||||
| 	contextName := "testContext0" | ||||
| 	_, err = client.New(contextName) | ||||
| 	if err != nil { | ||||
| 		t.Errorf("couldn't initialise a new client with context %s: %s", contextName, err) | ||||
| 	} | ||||
| 	contextName = "testContextFail0" | ||||
| 	_, err = client.New(contextName) | ||||
| 	if err == nil { | ||||
| 		t.Errorf("client.New(\"testContextFail0\") should have failed but didn't return an error") | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @ -4,14 +4,11 @@ import ( | ||||
| 	"errors" | ||||
| 	"fmt" | ||||
|  | ||||
| 	"coopcloud.tech/abra/pkg/context" | ||||
| 	commandconnPkg "coopcloud.tech/abra/pkg/upstream/commandconn" | ||||
| 	command "github.com/docker/cli/cli/command" | ||||
| 	dConfig "github.com/docker/cli/cli/config" | ||||
| 	context "github.com/docker/cli/cli/context" | ||||
| 	"github.com/docker/cli/cli/context/docker" | ||||
| 	contextStore "github.com/docker/cli/cli/context/store" | ||||
| 	cliflags "github.com/docker/cli/cli/flags" | ||||
| 	"github.com/moby/term" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| ) | ||||
|  | ||||
| @ -35,7 +32,7 @@ func CreateContext(contextName string, user string, port string) error { | ||||
|  | ||||
| // createContext interacts with Docker Context to create a Docker context config | ||||
| func createContext(name string, host string) error { | ||||
| 	s := NewDefaultDockerContextStore() | ||||
| 	s := context.NewDefaultDockerContextStore() | ||||
| 	contextMetadata := contextStore.Metadata{ | ||||
| 		Endpoints: make(map[string]interface{}), | ||||
| 		Name:      name, | ||||
| @ -83,46 +80,14 @@ func DeleteContext(name string) error { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	return NewDefaultDockerContextStore().Remove(name) | ||||
| 	return context.NewDefaultDockerContextStore().Remove(name) | ||||
| } | ||||
|  | ||||
| func GetContext(contextName string) (contextStore.Metadata, error) { | ||||
| 	ctx, err := NewDefaultDockerContextStore().GetMetadata(contextName) | ||||
| 	ctx, err := context.NewDefaultDockerContextStore().GetMetadata(contextName) | ||||
| 	if err != nil { | ||||
| 		return contextStore.Metadata{}, err | ||||
| 	} | ||||
|  | ||||
| 	return ctx, nil | ||||
| } | ||||
|  | ||||
| func GetContextEndpoint(ctx contextStore.Metadata) (string, error) { | ||||
| 	endpointmeta, ok := ctx.Endpoints["docker"].(context.EndpointMetaBase) | ||||
| 	if !ok { | ||||
| 		err := errors.New("context lacks Docker endpoint") | ||||
| 		return "", err | ||||
| 	} | ||||
| 	return endpointmeta.Host, nil | ||||
| } | ||||
|  | ||||
| func newContextStore(dir string, config contextStore.Config) contextStore.Store { | ||||
| 	return contextStore.New(dir, config) | ||||
| } | ||||
|  | ||||
| func NewDefaultDockerContextStore() *command.ContextStoreWithDefault { | ||||
| 	_, _, stderr := term.StdStreams() | ||||
| 	dockerConfig := dConfig.LoadDefaultConfigFile(stderr) | ||||
| 	contextDir := dConfig.ContextStoreDir() | ||||
| 	storeConfig := command.DefaultContextStoreConfig() | ||||
| 	store := newContextStore(contextDir, storeConfig) | ||||
|  | ||||
| 	opts := &cliflags.CommonOptions{Context: "default"} | ||||
|  | ||||
| 	dockerContextStore := &command.ContextStoreWithDefault{ | ||||
| 		Store: store, | ||||
| 		Resolver: func() (*command.DefaultContext, error) { | ||||
| 			return command.ResolveDefaultContext(opts, dockerConfig, storeConfig, stderr) | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	return dockerContextStore | ||||
| } | ||||
|  | ||||
| @ -1,80 +0,0 @@ | ||||
| package client_test | ||||
|  | ||||
| import ( | ||||
| 	"testing" | ||||
|  | ||||
| 	"coopcloud.tech/abra/pkg/client" | ||||
| 	dContext "github.com/docker/cli/cli/context" | ||||
| 	dCliContextStore "github.com/docker/cli/cli/context/store" | ||||
| ) | ||||
|  | ||||
| type TestContext struct { | ||||
| 	context           dCliContextStore.Metadata | ||||
| 	expected_endpoint string | ||||
| } | ||||
|  | ||||
| func dockerContext(host, key string) TestContext { | ||||
| 	dockerContext := dCliContextStore.Metadata{ | ||||
| 		Name:     "foo", | ||||
| 		Metadata: nil, | ||||
| 		Endpoints: map[string]interface{}{ | ||||
| 			key: dContext.EndpointMetaBase{ | ||||
| 				Host:          host, | ||||
| 				SkipTLSVerify: false, | ||||
| 			}, | ||||
| 		}, | ||||
| 	} | ||||
| 	return TestContext{ | ||||
| 		context:           dockerContext, | ||||
| 		expected_endpoint: host, | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestCreateContext(t *testing.T) { | ||||
| 	err := client.CreateContext("testContext0", "wronguser", "wrongport") | ||||
| 	if err == nil { | ||||
| 		t.Error("client.CreateContext(\"testContextCreate\", \"wronguser\", \"wrongport\") should have failed but didn't return an error") | ||||
| 	} | ||||
| 	err = client.CreateContext("testContext0", "", "") | ||||
| 	if err != nil { | ||||
| 		t.Errorf("Couldn't create context: %s", err) | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestDeleteContext(t *testing.T) { | ||||
| 	ensureTestState(1, 1) | ||||
| 	err := client.DeleteContext("default") | ||||
| 	if err == nil { | ||||
| 		t.Errorf("client.DeleteContext(\"default\") should have failed but didn't return an error") | ||||
| 	} | ||||
|  | ||||
| 	err = client.DeleteContext("testContext0") | ||||
| 	if err != nil { | ||||
| 		t.Errorf("client.DeleteContext(\"testContext0\") failed: %s", err) | ||||
| 	} | ||||
| 	err = client.DeleteContext("testContextFail0") | ||||
| 	if err == nil { | ||||
| 		t.Errorf("client.DeleteContext(\"testContextFail0\") should have failed (attempt to delete non-existent context) but didn't return an error") | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestGetContextEndpoint(t *testing.T) { | ||||
| 	var testDockerContexts = []TestContext{ | ||||
| 		dockerContext("ssh://foobar", "docker"), | ||||
| 		dockerContext("ssh://foobar", "k8"), | ||||
| 	} | ||||
| 	for _, context := range testDockerContexts { | ||||
| 		endpoint, err := client.GetContextEndpoint(context.context) | ||||
| 		if err != nil { | ||||
| 			if err.Error() != "context lacks Docker endpoint" { | ||||
| 				t.Error(err) | ||||
| 			} | ||||
| 		} else { | ||||
| 			if endpoint != context.expected_endpoint { | ||||
| 				t.Errorf("did not get correct context endpoint. Expected: %s, received: %s", context.expected_endpoint, endpoint) | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @ -117,8 +117,11 @@ func UpdateLabel(pattern, serviceName, label, recipeName string) error { | ||||
| 			continue | ||||
| 		} | ||||
|  | ||||
| 		discovered := false | ||||
| 		for oldLabel, value := range service.Deploy.Labels { | ||||
| 			if strings.HasPrefix(oldLabel, "coop-cloud") { | ||||
| 				discovered = true | ||||
|  | ||||
| 				bytes, err := ioutil.ReadFile(composeFile) | ||||
| 				if err != nil { | ||||
| 					return err | ||||
| @ -127,13 +130,19 @@ func UpdateLabel(pattern, serviceName, label, recipeName string) error { | ||||
| 				old := fmt.Sprintf("coop-cloud.${STACK_NAME}.version=%s", value) | ||||
| 				replacedBytes := strings.Replace(string(bytes), old, label, -1) | ||||
|  | ||||
| 				logrus.Debugf("updating '%s' to '%s' in '%s'", old, label, compose.Filename) | ||||
| 				logrus.Debugf("updating %s to %s in %s", old, label, compose.Filename) | ||||
|  | ||||
| 				if err := ioutil.WriteFile(compose.Filename, []byte(replacedBytes), 0644); err != nil { | ||||
| 					return err | ||||
| 				} | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		if !discovered { | ||||
| 			logrus.Warn("no existing label found, cannot continue...") | ||||
| 			logrus.Fatalf("add '%s' manually, automagic insertion not supported yet", label) | ||||
| 		} | ||||
|  | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
|  | ||||
							
								
								
									
										44
									
								
								pkg/context/context.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								pkg/context/context.go
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,44 @@ | ||||
| package context | ||||
|  | ||||
| import ( | ||||
| 	"errors" | ||||
|  | ||||
| 	"github.com/docker/cli/cli/command" | ||||
| 	dConfig "github.com/docker/cli/cli/config" | ||||
| 	"github.com/docker/cli/cli/context" | ||||
| 	contextStore "github.com/docker/cli/cli/context/store" | ||||
| 	cliflags "github.com/docker/cli/cli/flags" | ||||
| 	"github.com/moby/term" | ||||
| ) | ||||
|  | ||||
| func NewDefaultDockerContextStore() *command.ContextStoreWithDefault { | ||||
| 	_, _, stderr := term.StdStreams() | ||||
| 	dockerConfig := dConfig.LoadDefaultConfigFile(stderr) | ||||
| 	contextDir := dConfig.ContextStoreDir() | ||||
| 	storeConfig := command.DefaultContextStoreConfig() | ||||
| 	store := newContextStore(contextDir, storeConfig) | ||||
|  | ||||
| 	opts := &cliflags.CommonOptions{Context: "default"} | ||||
|  | ||||
| 	dockerContextStore := &command.ContextStoreWithDefault{ | ||||
| 		Store: store, | ||||
| 		Resolver: func() (*command.DefaultContext, error) { | ||||
| 			return command.ResolveDefaultContext(opts, dockerConfig, storeConfig, stderr) | ||||
| 		}, | ||||
| 	} | ||||
|  | ||||
| 	return dockerContextStore | ||||
| } | ||||
|  | ||||
| func GetContextEndpoint(ctx contextStore.Metadata) (string, error) { | ||||
| 	endpointmeta, ok := ctx.Endpoints["docker"].(context.EndpointMetaBase) | ||||
| 	if !ok { | ||||
| 		err := errors.New("context lacks Docker endpoint") | ||||
| 		return "", err | ||||
| 	} | ||||
| 	return endpointmeta.Host, nil | ||||
| } | ||||
|  | ||||
| func newContextStore(dir string, config contextStore.Config) contextStore.Store { | ||||
| 	return contextStore.New(dir, config) | ||||
| } | ||||
							
								
								
									
										442
									
								
								pkg/ssh/ssh.go
									
									
									
									
									
								
							
							
						
						
									
										442
									
								
								pkg/ssh/ssh.go
									
									
									
									
									
								
							| @ -3,18 +3,35 @@ package ssh | ||||
| import ( | ||||
| 	"bufio" | ||||
| 	"bytes" | ||||
| 	"crypto/sha256" | ||||
| 	"encoding/base64" | ||||
| 	"fmt" | ||||
| 	"io" | ||||
| 	"net" | ||||
| 	"os" | ||||
| 	"os/user" | ||||
| 	"path/filepath" | ||||
| 	"strings" | ||||
| 	"sync" | ||||
| 	"time" | ||||
|  | ||||
| 	"coopcloud.tech/abra/pkg/context" | ||||
| 	"github.com/AlecAivazis/survey/v2" | ||||
| 	dockerSSHPkg "github.com/docker/cli/cli/connhelper/ssh" | ||||
| 	sshPkg "github.com/gliderlabs/ssh" | ||||
| 	"github.com/kevinburke/ssh_config" | ||||
| 	"github.com/sfreiberg/simplessh" | ||||
| 	"github.com/sirupsen/logrus" | ||||
| 	"golang.org/x/crypto/ssh" | ||||
| 	"golang.org/x/crypto/ssh/agent" | ||||
| 	"golang.org/x/crypto/ssh/knownhosts" | ||||
| ) | ||||
|  | ||||
| var KnownHostsPath = filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts") | ||||
|  | ||||
| type Client struct { | ||||
| 	SSHClient *ssh.Client | ||||
| } | ||||
|  | ||||
| // HostConfig is a SSH host config. | ||||
| type HostConfig struct { | ||||
| 	Host         string | ||||
| @ -23,61 +40,39 @@ type HostConfig struct { | ||||
| 	User         string | ||||
| } | ||||
|  | ||||
| // GetHostConfig retrieves a ~/.ssh/config config for a host. | ||||
| func GetHostConfig(hostname, username, port string) (HostConfig, error) { | ||||
| 	var hostConfig HostConfig | ||||
|  | ||||
| 	var host, idf string | ||||
|  | ||||
| 	if host = ssh_config.Get(hostname, "Hostname"); host == "" { | ||||
| 		logrus.Debugf("no hostname found in SSH config, assuming %s", hostname) | ||||
| 		host = hostname | ||||
| // Exec cmd on the remote host and return stderr and stdout | ||||
| func (c *Client) Exec(cmd string) ([]byte, error) { | ||||
| 	session, err := c.SSHClient.NewSession() | ||||
| 	if err != nil { | ||||
| 		return nil, err | ||||
| 	} | ||||
| 	defer session.Close() | ||||
|  | ||||
| 	if username == "" { | ||||
| 		if username = ssh_config.Get(hostname, "User"); username == "" { | ||||
| 			systemUser, err := user.Current() | ||||
| 			if err != nil { | ||||
| 				return hostConfig, err | ||||
| 			} | ||||
| 			logrus.Debugf("no username found in SSH config or passed on command-line, assuming %s", username) | ||||
| 			username = systemUser.Username | ||||
| 		} | ||||
| 	} | ||||
| 	return session.CombinedOutput(cmd) | ||||
| } | ||||
|  | ||||
| 	if port == "" { | ||||
| 		if port = ssh_config.Get(hostname, "Port"); port == "" { | ||||
| 			logrus.Debugf("no port found in SSH config or passed on command-line, assuming 22") | ||||
| 			port = "22" | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	idf = ssh_config.Get(hostname, "IdentityFile") | ||||
|  | ||||
| 	hostConfig.Host = host | ||||
| 	if idf != "" { | ||||
| 		hostConfig.IdentityFile = idf | ||||
| 	} | ||||
| 	hostConfig.Port = port | ||||
| 	hostConfig.User = username | ||||
|  | ||||
| 	logrus.Debugf("constructed SSH config %s for %s", hostConfig, hostname) | ||||
|  | ||||
| 	return hostConfig, nil | ||||
| // Close the underlying SSH connection | ||||
| func (c *Client) Close() error { | ||||
| 	return c.SSHClient.Close() | ||||
| } | ||||
|  | ||||
| // New creates a new SSH client connection. | ||||
| func New(domainName, sshAuth, username, port string) (*simplessh.Client, error) { | ||||
| 	var client *simplessh.Client | ||||
| func New(domainName, sshAuth, username, port string) (*Client, error) { | ||||
| 	var client *Client | ||||
|  | ||||
| 	hostConfig, err := GetHostConfig(domainName, username, port) | ||||
| 	ctxConnDetails, err := GetContextConnDetails(domainName) | ||||
| 	if err != nil { | ||||
| 		return client, err | ||||
| 		return client, nil | ||||
| 	} | ||||
|  | ||||
| 	if sshAuth == "identity-file" { | ||||
| 		var err error | ||||
| 		client, err = simplessh.ConnectWithAgentTimeout(hostConfig.Host, hostConfig.User, 5*time.Second) | ||||
| 		client, err = connectWithAgentTimeout( | ||||
| 			ctxConnDetails.Host, | ||||
| 			ctxConnDetails.User, | ||||
| 			ctxConnDetails.Port, | ||||
| 			5*time.Second, | ||||
| 		) | ||||
| 		if err != nil { | ||||
| 			return client, err | ||||
| 		} | ||||
| @ -91,7 +86,13 @@ func New(domainName, sshAuth, username, port string) (*simplessh.Client, error) | ||||
| 		} | ||||
|  | ||||
| 		var err error | ||||
| 		client, err = simplessh.ConnectWithPasswordTimeout(hostConfig.Host, hostConfig.User, password, 5*time.Second) | ||||
| 		client, err = connectWithPasswordTimeout( | ||||
| 			ctxConnDetails.Host, | ||||
| 			ctxConnDetails.User, | ||||
| 			ctxConnDetails.Port, | ||||
| 			password, | ||||
| 			5*time.Second, | ||||
| 		) | ||||
| 		if err != nil { | ||||
| 			return client, err | ||||
| 		} | ||||
| @ -100,8 +101,7 @@ func New(domainName, sshAuth, username, port string) (*simplessh.Client, error) | ||||
| 	return client, nil | ||||
| } | ||||
|  | ||||
| // sudoWriter supports sudo command handling. | ||||
| // https://github.com/sfreiberg/simplessh/blob/master/simplessh.go | ||||
| // sudoWriter supports sudo command handling | ||||
| type sudoWriter struct { | ||||
| 	b     bytes.Buffer | ||||
| 	pw    string | ||||
| @ -109,8 +109,7 @@ type sudoWriter struct { | ||||
| 	m     sync.Mutex | ||||
| } | ||||
|  | ||||
| // Write satisfies the write interface for sudoWriter. | ||||
| // https://github.com/sfreiberg/simplessh/blob/master/simplessh.go | ||||
| // Write satisfies the write interface for sudoWriter | ||||
| func (w *sudoWriter) Write(p []byte) (int, error) { | ||||
| 	if string(p) == "sudo_password" { | ||||
| 		w.stdin.Write([]byte(w.pw + "\n")) | ||||
| @ -124,9 +123,8 @@ func (w *sudoWriter) Write(p []byte) (int, error) { | ||||
| 	return w.b.Write(p) | ||||
| } | ||||
|  | ||||
| // RunSudoCmd runs SSH commands and streams output. | ||||
| // https://github.com/sfreiberg/simplessh/blob/master/simplessh.go | ||||
| func RunSudoCmd(cmd, passwd string, cl *simplessh.Client) error { | ||||
| // RunSudoCmd runs SSH commands and streams output | ||||
| func RunSudoCmd(cmd, passwd string, cl *Client) error { | ||||
| 	session, err := cl.SSHClient.NewSession() | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| @ -170,9 +168,8 @@ func RunSudoCmd(cmd, passwd string, cl *simplessh.Client) error { | ||||
| 	return err | ||||
| } | ||||
|  | ||||
| // Exec runs a command on a remote and streams output. | ||||
| // https://github.com/sfreiberg/simplessh/blob/master/simplessh.go | ||||
| func Exec(cmd string, cl *simplessh.Client) error { | ||||
| // Exec runs a command on a remote and streams output | ||||
| func Exec(cmd string, cl *Client) error { | ||||
| 	session, err := cl.SSHClient.NewSession() | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| @ -224,3 +221,338 @@ func Exec(cmd string, cl *simplessh.Client) error { | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| // EnsureKnowHostsFiles ensures that ~/.ssh/known_hosts is created | ||||
| func EnsureKnowHostsFiles() error { | ||||
| 	if _, err := os.Stat(KnownHostsPath); os.IsNotExist(err) { | ||||
| 		logrus.Debugf("missing %s, creating now", KnownHostsPath) | ||||
| 		file, err := os.OpenFile(KnownHostsPath, os.O_CREATE, 0600) | ||||
| 		if err != nil { | ||||
| 			return err | ||||
| 		} | ||||
| 		file.Close() | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| // GetHostKey checks if a host key is registered in the ~/.ssh/known_hosts file | ||||
| func GetHostKey(hostname string) (bool, sshPkg.PublicKey, error) { | ||||
| 	var hostKey sshPkg.PublicKey | ||||
|  | ||||
| 	ctxConnDetails, err := GetContextConnDetails(hostname) | ||||
| 	if err != nil { | ||||
| 		return false, hostKey, err | ||||
| 	} | ||||
|  | ||||
| 	if err := EnsureKnowHostsFiles(); err != nil { | ||||
| 		return false, hostKey, err | ||||
| 	} | ||||
|  | ||||
| 	file, err := os.Open(KnownHostsPath) | ||||
| 	if err != nil { | ||||
| 		return false, hostKey, err | ||||
| 	} | ||||
| 	defer file.Close() | ||||
|  | ||||
| 	scanner := bufio.NewScanner(file) | ||||
| 	for scanner.Scan() { | ||||
| 		fields := strings.Split(scanner.Text(), " ") | ||||
| 		if len(fields) != 3 { | ||||
| 			continue | ||||
| 		} | ||||
|  | ||||
| 		hostnameAndPort := fmt.Sprintf("%s:%s", ctxConnDetails.Host, ctxConnDetails.Port) | ||||
| 		hashed := knownhosts.Normalize(hostnameAndPort) | ||||
|  | ||||
| 		if strings.Contains(fields[0], hashed) { | ||||
| 			var err error | ||||
| 			hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes()) | ||||
| 			if err != nil { | ||||
| 				return false, hostKey, fmt.Errorf("error parsing server SSH host key %q: %v", fields[2], err) | ||||
| 			} | ||||
| 			break | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if hostKey != nil { | ||||
| 		logrus.Debugf("server SSH host key present in ~/.ssh/known_hosts for %s", hostname) | ||||
| 		return true, hostKey, nil | ||||
| 	} | ||||
|  | ||||
| 	return false, hostKey, nil | ||||
| } | ||||
|  | ||||
| // InsertHostKey adds a new host key to the ~/.ssh/known_hosts file | ||||
| func InsertHostKey(hostname string, remote net.Addr, pubKey ssh.PublicKey) error { | ||||
| 	file, err := os.OpenFile(KnownHostsPath, os.O_APPEND|os.O_WRONLY, 0600) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
| 	defer file.Close() | ||||
|  | ||||
| 	hashedHostname := knownhosts.Normalize(hostname) | ||||
| 	lineHostname := knownhosts.Line([]string{hashedHostname}, pubKey) | ||||
| 	_, err = file.WriteString(fmt.Sprintf("%s\n", lineHostname)) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	hashedRemote := knownhosts.Normalize(remote.String()) | ||||
| 	lineRemote := knownhosts.Line([]string{hashedRemote}, pubKey) | ||||
| 	_, err = file.WriteString(fmt.Sprintf("%s\n", lineRemote)) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	logrus.Debugf("SSH host key generated: %s", lineHostname) | ||||
| 	logrus.Debugf("SSH host key generated: %s", lineRemote) | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| // HostKeyAddCallback ensures server ssh host keys are handled | ||||
| func HostKeyAddCallback(hostnameAndPort string, remote net.Addr, pubKey ssh.PublicKey) error { | ||||
| 	exists, _, err := GetHostKey(hostnameAndPort) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	if exists { | ||||
| 		hostname := strings.Split(hostnameAndPort, ":")[0] | ||||
| 		logrus.Debugf("server SSH host key found for %s, moving on", hostname) | ||||
| 		return nil | ||||
| 	} | ||||
|  | ||||
| 	if !exists { | ||||
| 		hostname := strings.Split(hostnameAndPort, ":")[0] | ||||
| 		parsedPubKey := FingerprintSHA256(pubKey) | ||||
|  | ||||
| 		fmt.Printf(fmt.Sprintf(` | ||||
| You are attempting to make an SSH connection to a server but there is no entry | ||||
| in your ~/.ssh/known_hosts file which confirms that this is indeed the server | ||||
| you want to connect to. Please take a moment to validate the following SSH host | ||||
| key, it is important. | ||||
|  | ||||
|     Host:        %s | ||||
|     Fingerprint: %s | ||||
|  | ||||
| If this is confusing to you, you can read the article below and learn how to | ||||
| validate this fingerprint safely. Thanks to the comrades at cyberia.club for | ||||
| writing this extensive guide <3 | ||||
|  | ||||
|     https://sequentialread.com/understanding-the-secure-shell-protocol-ssh/ | ||||
|  | ||||
| `, hostname, parsedPubKey)) | ||||
|  | ||||
| 		response := false | ||||
| 		prompt := &survey.Confirm{ | ||||
| 			Message: "are you sure you trust this host key?", | ||||
| 		} | ||||
|  | ||||
| 		if err := survey.AskOne(prompt, &response); err != nil { | ||||
| 			return err | ||||
| 		} | ||||
|  | ||||
| 		if !response { | ||||
| 			logrus.Fatal("exiting as requested") | ||||
| 		} | ||||
|  | ||||
| 		logrus.Debugf("attempting to insert server SSH host key for %s, %s", hostnameAndPort, remote) | ||||
|  | ||||
| 		if err := InsertHostKey(hostnameAndPort, remote, pubKey); err != nil { | ||||
| 			return err | ||||
| 		} | ||||
|  | ||||
| 		logrus.Infof("successfully added server SSH host key for %s", hostname) | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| // connect makes the SSH connection | ||||
| func connect(username, host, port string, authMethod ssh.AuthMethod, timeout time.Duration) (*Client, error) { | ||||
| 	config := &ssh.ClientConfig{ | ||||
| 		User:            username, | ||||
| 		Auth:            []ssh.AuthMethod{authMethod}, | ||||
| 		HostKeyCallback: HostKeyAddCallback, // the main reason why we fork | ||||
| 	} | ||||
|  | ||||
| 	hostnameAndPort := fmt.Sprintf("%s:%s", host, port) | ||||
|  | ||||
| 	logrus.Debugf("tcp dialing %s", hostnameAndPort) | ||||
|  | ||||
| 	var conn net.Conn | ||||
| 	var err error | ||||
| 	conn, err = net.DialTimeout("tcp", hostnameAndPort, timeout) | ||||
| 	if err != nil { | ||||
| 		logrus.Debugf("tcp dialing %s failed, trying via ~/.ssh/config", hostnameAndPort) | ||||
| 		hostConfig, err := GetHostConfig(host, username, port) | ||||
| 		if err != nil { | ||||
| 			return nil, err | ||||
| 		} | ||||
| 		conn, err = net.DialTimeout("tcp", fmt.Sprintf("%s:%s", hostConfig.Host, hostConfig.Port), timeout) | ||||
| 		if err != nil { | ||||
| 			return nil, err | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	sshConn, chans, reqs, err := ssh.NewClientConn(conn, hostnameAndPort, config) | ||||
| 	if err != nil { | ||||
| 		return nil, err | ||||
| 	} | ||||
|  | ||||
| 	client := ssh.NewClient(sshConn, chans, reqs) | ||||
| 	c := &Client{SSHClient: client} | ||||
|  | ||||
| 	return c, nil | ||||
| } | ||||
|  | ||||
| func connectWithAgentTimeout(host, username, port string, timeout time.Duration) (*Client, error) { | ||||
| 	sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) | ||||
| 	if err != nil { | ||||
| 		return nil, err | ||||
| 	} | ||||
|  | ||||
| 	authMethod := ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers) | ||||
|  | ||||
| 	return connect(username, host, port, authMethod, timeout) | ||||
| } | ||||
|  | ||||
| func connectWithPasswordTimeout(host, username, port, pass string, timeout time.Duration) (*Client, error) { | ||||
| 	authMethod := ssh.Password(pass) | ||||
|  | ||||
| 	return connect(username, host, port, authMethod, timeout) | ||||
| } | ||||
|  | ||||
| // EnsureHostKey ensures that a host key trusted and added to the ~/.ssh/known_hosts file | ||||
| func EnsureHostKey(hostname string) error { | ||||
| 	if hostname == "default" || hostname == "local" { | ||||
| 		logrus.Debugf("not checking server SSH host key against local/default target") | ||||
| 		return nil | ||||
| 	} | ||||
|  | ||||
| 	exists, _, err := GetHostKey(hostname) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
| 	if exists { | ||||
| 		return nil | ||||
| 	} | ||||
|  | ||||
| 	ctxConnDetails, err := GetContextConnDetails(hostname) | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	_, err = connectWithAgentTimeout( | ||||
| 		ctxConnDetails.Host, | ||||
| 		ctxConnDetails.User, | ||||
| 		ctxConnDetails.Port, | ||||
| 		5*time.Second, | ||||
| 	) | ||||
|  | ||||
| 	if err != nil { | ||||
| 		return err | ||||
| 	} | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| // FingerprintSHA256 generates the SHA256 fingerprint for a server SSH host key | ||||
| func FingerprintSHA256(key ssh.PublicKey) string { | ||||
| 	hash := sha256.Sum256(key.Marshal()) | ||||
| 	b64hash := base64.StdEncoding.EncodeToString(hash[:]) | ||||
| 	trimmed := strings.TrimRight(b64hash, "=") | ||||
| 	return fmt.Sprintf("SHA256:%s", trimmed) | ||||
| } | ||||
|  | ||||
| // GetContextConnDetails retrieves SSH connection details from a docker context endpoint | ||||
| func GetContextConnDetails(serverName string) (*dockerSSHPkg.Spec, error) { | ||||
| 	dockerContextStore := context.NewDefaultDockerContextStore() | ||||
| 	contexts, err := dockerContextStore.Store.List() | ||||
| 	if err != nil { | ||||
| 		return &dockerSSHPkg.Spec{}, err | ||||
| 	} | ||||
|  | ||||
| 	if strings.Contains(serverName, ":") { | ||||
| 		serverName = strings.Split(serverName, ":")[0] | ||||
| 	} | ||||
|  | ||||
| 	for _, ctx := range contexts { | ||||
| 		endpoint, err := context.GetContextEndpoint(ctx) | ||||
| 		if err != nil && strings.Contains(err.Error(), "does not exist") { | ||||
| 			// No local context found, we can continue safely | ||||
| 			continue | ||||
| 		} | ||||
| 		if ctx.Name == serverName { | ||||
| 			ctxConnDetails, err := dockerSSHPkg.ParseURL(endpoint) | ||||
| 			if err != nil { | ||||
| 				return &dockerSSHPkg.Spec{}, err | ||||
| 			} | ||||
| 			logrus.Debugf("found context connection details %v for %s", ctxConnDetails, serverName) | ||||
| 			return ctxConnDetails, nil | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	hostConfig, err := GetHostConfig(serverName, "", "") | ||||
| 	if err != nil { | ||||
| 		return &dockerSSHPkg.Spec{}, err | ||||
| 	} | ||||
|  | ||||
| 	logrus.Debugf("couldn't find a docker context matching %s", serverName) | ||||
| 	logrus.Debugf("searching ~/.ssh/config for a Host entry for %s", serverName) | ||||
|  | ||||
| 	connDetails := &dockerSSHPkg.Spec{ | ||||
| 		Host: hostConfig.Host, | ||||
| 		User: hostConfig.User, | ||||
| 		Port: hostConfig.Port, | ||||
| 	} | ||||
|  | ||||
| 	logrus.Debugf("using %v from ~/.ssh/config for connection details", connDetails) | ||||
|  | ||||
| 	return connDetails, nil | ||||
| } | ||||
|  | ||||
| // GetHostConfig retrieves a ~/.ssh/config config for a host. | ||||
| func GetHostConfig(hostname, username, port string) (HostConfig, error) { | ||||
| 	var hostConfig HostConfig | ||||
|  | ||||
| 	var host, idf string | ||||
|  | ||||
| 	if host = ssh_config.Get(hostname, "Hostname"); host == "" { | ||||
| 		logrus.Debugf("no hostname found in SSH config, assuming %s", hostname) | ||||
| 		host = hostname | ||||
| 	} | ||||
|  | ||||
| 	if username == "" { | ||||
| 		if username = ssh_config.Get(hostname, "User"); username == "" { | ||||
| 			systemUser, err := user.Current() | ||||
| 			if err != nil { | ||||
| 				return hostConfig, err | ||||
| 			} | ||||
| 			logrus.Debugf("no username found in SSH config or passed on command-line, assuming %s", username) | ||||
| 			username = systemUser.Username | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if port == "" { | ||||
| 		if port = ssh_config.Get(hostname, "Port"); port == "" { | ||||
| 			logrus.Debugf("no port found in SSH config or passed on command-line, assuming 22") | ||||
| 			port = "22" | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	idf = ssh_config.Get(hostname, "IdentityFile") | ||||
|  | ||||
| 	hostConfig.Host = host | ||||
| 	if idf != "" { | ||||
| 		hostConfig.IdentityFile = idf | ||||
| 	} | ||||
| 	hostConfig.Port = port | ||||
| 	hostConfig.User = username | ||||
|  | ||||
| 	logrus.Debugf("constructed SSH config %s for %s", hostConfig, hostname) | ||||
|  | ||||
| 	return hostConfig, nil | ||||
| } | ||||
|  | ||||
| @ -5,6 +5,7 @@ import ( | ||||
| 	"net" | ||||
| 	"net/url" | ||||
|  | ||||
| 	sshPkg "coopcloud.tech/abra/pkg/ssh" | ||||
| 	"github.com/docker/cli/cli/connhelper" | ||||
| 	"github.com/docker/cli/cli/connhelper/ssh" | ||||
| 	"github.com/docker/cli/cli/context/docker" | ||||
| @ -23,19 +24,22 @@ func GetConnectionHelper(daemonURL string) (*connhelper.ConnectionHelper, error) | ||||
| } | ||||
|  | ||||
| func getConnectionHelper(daemonURL string, sshFlags []string) (*connhelper.ConnectionHelper, error) { | ||||
| 	u, err := url.Parse(daemonURL) | ||||
| 	url, err := url.Parse(daemonURL) | ||||
| 	if err != nil { | ||||
| 		return nil, err | ||||
| 	} | ||||
| 	switch scheme := u.Scheme; scheme { | ||||
| 	switch scheme := url.Scheme; scheme { | ||||
| 	case "ssh": | ||||
| 		sp, err := ssh.ParseURL(daemonURL) | ||||
| 		ctxConnDetails, err := ssh.ParseURL(daemonURL) | ||||
| 		if err != nil { | ||||
| 			return nil, errors.Wrap(err, "ssh host connection is not valid") | ||||
| 		} | ||||
| 		if err := sshPkg.EnsureHostKey(ctxConnDetails.Host); err != nil { | ||||
| 			return nil, err | ||||
| 		} | ||||
| 		return &connhelper.ConnectionHelper{ | ||||
| 			Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) { | ||||
| 				return New(ctx, "ssh", append(sshFlags, sp.Args("docker", "system", "dial-stdio")...)...) | ||||
| 				return New(ctx, "ssh", append(sshFlags, ctxConnDetails.Args("docker", "system", "dial-stdio")...)...) | ||||
| 			}, | ||||
| 			Host: "http://docker.example.com", | ||||
| 		}, nil | ||||
|  | ||||
| @ -3,10 +3,13 @@ package stack // https://github.com/docker/cli/blob/master/cli/command/stack/swa | ||||
| import ( | ||||
| 	"context" | ||||
| 	"fmt" | ||||
| 	"io" | ||||
| 	"io/ioutil" | ||||
| 	"strings" | ||||
|  | ||||
| 	abraClient "coopcloud.tech/abra/pkg/client" | ||||
| 	"coopcloud.tech/abra/pkg/upstream/convert" | ||||
| 	"github.com/docker/cli/cli/command/service/progress" | ||||
| 	composetypes "github.com/docker/cli/cli/compose/types" | ||||
| 	"github.com/docker/docker/api/types" | ||||
| 	"github.com/docker/docker/api/types/container" | ||||
| @ -346,6 +349,7 @@ func deployServices( | ||||
| 		existingServiceMap[service.Spec.Name] = service | ||||
| 	} | ||||
|  | ||||
| 	var serviceIDs []string | ||||
| 	for internalName, serviceSpec := range services { | ||||
| 		var ( | ||||
| 			name        = namespace.Scope(internalName) | ||||
| @ -405,6 +409,8 @@ func deployServices( | ||||
| 				return errors.Wrapf(err, "failed to update service %s", name) | ||||
| 			} | ||||
|  | ||||
| 			serviceIDs = append(serviceIDs, service.ID) | ||||
|  | ||||
| 			for _, warning := range response.Warnings { | ||||
| 				logrus.Warn(warning) | ||||
| 			} | ||||
| @ -418,11 +424,35 @@ func deployServices( | ||||
| 				createOpts.QueryRegistry = true | ||||
| 			} | ||||
|  | ||||
| 			if _, err := cl.ServiceCreate(ctx, serviceSpec, createOpts); err != nil { | ||||
| 			serviceCreateResponse, err := cl.ServiceCreate(ctx, serviceSpec, createOpts) | ||||
| 			if err != nil { | ||||
| 				return errors.Wrapf(err, "failed to create service %s", name) | ||||
| 			} | ||||
|  | ||||
| 			serviceIDs = append(serviceIDs, serviceCreateResponse.ID) | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	logrus.Infof("waiting for services to converge: %s", strings.Join(serviceIDs, ", ")) | ||||
|  | ||||
| 	ch := make(chan error, len(serviceIDs)) | ||||
| 	for _, serviceID := range serviceIDs { | ||||
| 		logrus.Debugf("waiting on %s to converge", serviceID) | ||||
| 		go func(s string) { | ||||
| 			ch <- waitOnService(ctx, cl, s) | ||||
| 		}(serviceID) | ||||
| 	} | ||||
|  | ||||
| 	for _, serviceID := range serviceIDs { | ||||
| 		err := <-ch | ||||
| 		if err != nil { | ||||
| 			return err | ||||
| 		} | ||||
| 		logrus.Debugf("assuming %s converged successfully", serviceID) | ||||
| 	} | ||||
|  | ||||
| 	logrus.Info("services converged 👌") | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|  | ||||
| @ -437,3 +467,17 @@ func getStackSecrets(ctx context.Context, dockerclient client.APIClient, namespa | ||||
| func getStackConfigs(ctx context.Context, dockerclient client.APIClient, namespace string) ([]swarm.Config, error) { | ||||
| 	return dockerclient.ConfigList(ctx, types.ConfigListOptions{Filters: getStackFilter(namespace)}) | ||||
| } | ||||
|  | ||||
| // https://github.com/docker/cli/blob/master/cli/command/service/helpers.go | ||||
| // https://github.com/docker/cli/blob/master/cli/command/service/progress/progress.go | ||||
| func waitOnService(ctx context.Context, cl *dockerclient.Client, serviceID string) error { | ||||
| 	errChan := make(chan error, 1) | ||||
| 	pipeReader, pipeWriter := io.Pipe() | ||||
|  | ||||
| 	go func() { | ||||
| 		errChan <- progress.ServiceProgress(ctx, cl, serviceID, pipeWriter) | ||||
| 	}() | ||||
|  | ||||
| 	go io.Copy(ioutil.Discard, pipeReader) | ||||
| 	return <-errChan | ||||
| } | ||||
|  | ||||
| @ -2,6 +2,15 @@ | ||||
|  | ||||
| ABRA_VERSION="0.3.0-alpha" | ||||
| ABRA_RELEASE_URL="https://git.coopcloud.tech/api/v1/repos/coop-cloud/abra/releases/tags/$ABRA_VERSION" | ||||
| RC_VERSION="0.3.1-alpha-rc1" | ||||
| RC_VERSION_URL="https://git.coopcloud.tech/api/v1/repos/coop-cloud/abra/releases/tags/$RC_VERSION" | ||||
|  | ||||
| for arg in "$@"; do | ||||
|   if [ "$arg" == "--rc" ]; then | ||||
|     ABRA_VERSION="$RC_VERSION" | ||||
|     ABRA_RELEASE_URL="$RC_VERSION_URL" | ||||
|   fi | ||||
| done | ||||
|  | ||||
| function show_banner { | ||||
|   echo "" | ||||
| @ -35,6 +44,7 @@ function install_abra_release { | ||||
|     exit 1 | ||||
|   fi | ||||
|  | ||||
|  | ||||
|   # FIXME: support different architectures | ||||
|   PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m) | ||||
|   FILENAME="abra_"$ABRA_VERSION"_"$PLATFORM"" | ||||
| @ -79,6 +89,7 @@ function install_abra_release { | ||||
|   echo "abra installed to $HOME/.local/bin/abra" | ||||
| } | ||||
|  | ||||
|  | ||||
| function run_installation { | ||||
|   show_banner | ||||
|   install_abra_release | ||||
|  | ||||
		Reference in New Issue
	
	Block a user