Skip to content

Commit

Permalink
#288: Separate down from clean. (#301)
Browse files Browse the repository at this point in the history
* Still needs a test case to be written
* #288 - Add a test case
* First pass of logic changes for #288
* #288 wip
* Simplify the ssh status method!
* Remove ssh_showkeys
* stability improvements - almost done!
* getting close
* Update addkey.go, interface.go, and 3 more files...
* Remove test case for show-keys example
* Adjust error action for issues found via get
* Reimplement some of the logic. Looking mighty fine and predictable now.
* Cleanup output of clean
* Cleanup
* Update autoremove values
  • Loading branch information
fubarhouse committed Mar 6, 2021
1 parent 30172a8 commit a99d049
Show file tree
Hide file tree
Showing 17 changed files with 182 additions and 314 deletions.
8 changes: 8 additions & 0 deletions .github/workflows/pygmy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,14 @@ jobs:
lando destroy -y;
cd ../../;
- name: Test the down command
run: |
./pygmy-go-linux-x86 --config examples/pygmy.basic.yml down | grep 'Successfully stopped amazeeio';
./pygmy-go-linux-x86 --config examples/pygmy.basic.yml status | grep '\[ \] amazeeio-' | grep 'is not running';
./pygmy-go-linux-x86 --config examples/pygmy.basic.yml status | grep 'Running as container amazeeio-' && false || true;
./pygmy-go-linux-x86 --config examples/pygmy.basic.yml up;
./pygmy-go-linux-x86 --config examples/pygmy.basic.yml status | grep 'Running as container amazeeio-' && true || false;
- name: Cowsay test
run: ./pygmy-go-linux-x86 --config examples/pygmy.basic.yml up | grep 'holy ship' || true;

Expand Down
32 changes: 28 additions & 4 deletions cmd/addkey.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"fmt"
"os"

"github.com/fubarhouse/pygmy-go/service/interface/docker"
"github.com/fubarhouse/pygmy-go/service/library"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
Expand All @@ -32,16 +33,35 @@ import (
// addkeyCmd is the SSH key add command.
var addkeyCmd = &cobra.Command{
Use: "addkey",
Example: "pygmy addkey ~/.ssh/id_rsa",
Example: "pygmy addkey --key ~/.ssh/id_rsa",
Short: "Add/re-add an SSH key to the agent",
Long: `Add or re-add an SSH key to Pygmy's SSH Agent by specifying the path to the private key.`,
Run: func(cmd *cobra.Command, args []string) {

Key, _ := cmd.Flags().GetString("key")
Keys := []string{}

e := library.SshKeyAdd(c, Key, 0)
if e != nil {
fmt.Println(e)
if Key != "" {
Keys = append(Keys, Key)
} else {
library.Setup(&c)
Keys = c.Keys
}

for _, k := range Keys {
if e := library.SshKeyAdd(c, k); e != nil {
fmt.Println(e)
}
}

for _, s := range c.SortedServices {
service := c.Services[s]
purpose, _ := service.GetFieldString("purpose")
if purpose == "sshagent" {
name, _ := service.GetFieldString("name")
d, _ := docker.DockerExec(name, "ssh-add -l")
fmt.Println(string(d))
}
}

},
Expand All @@ -52,6 +72,10 @@ func init() {
homedir, _ := homedir.Dir()
keypath := fmt.Sprintf("%v%v.ssh%vid_rsa", homedir, string(os.PathSeparator), string(os.PathSeparator))

if _, err := os.Stat(keypath); err == nil {
keypath = ""
}

rootCmd.AddCommand(addkeyCmd)
addkeyCmd.Flags().StringP("key", "", keypath, "Path of SSH key to add")

Expand Down
5 changes: 0 additions & 5 deletions examples/pygmy.basic.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,6 @@ services:
Labels:
- pygmy.enable: false

amazeeio-ssh-agent-show-keys:
Config:
Labels:
- pygmy.enable: false

amazeeio-portainer:
Config:
Image: portainer/portainer
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ github.com/spf13/cobra v1.0.0 h1:6m/oheQuQ13N9ks4hubMG6BnvwOeaJrqSPLahSnczz8=
github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4=
github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI=
github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M=
github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
Expand Down Expand Up @@ -421,6 +422,7 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gotest.tools/v3 v3.0.2 h1:kG1BFyqVHuQoVQiR1bWGnfz/fmHvvuiSPIV7rvl360E=
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
Expand Down
153 changes: 91 additions & 62 deletions service/interface/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,25 @@ import (
// not found in the daemon.
func (Service *Service) Setup() error {
if Service.Config.Image == "" {
return nil
return fmt.Errorf("image reference is nil value")
}

found := false
images, _ := docker.DockerImageList()
for _, image := range images {
if strings.Contains(fmt.Sprint(image.RepoTags), Service.Config.Image) {
return nil
found = true
}
}

msg, err := docker.DockerPull(Service.Config.Image)
if msg != "" {
fmt.Println(msg)
}

if err != nil {
fmt.Println(err)
if !found {
if msg, err := docker.DockerPull(Service.Config.Image); err != nil {
return err
} else if strings.Contains(msg, "already up to date") {
return fmt.Errorf(msg)
}
} else {
return fmt.Errorf("image already in registry, skipping")
}

return nil
Expand Down Expand Up @@ -68,14 +70,16 @@ func (Service *Service) Start() error {
return nil
}

if purpose == "addkeys" || purpose == "showkeys" {
if purpose == "addkeys" {
if e := docker.DockerKill(name); e != nil {
fmt.Sprintln(e)
}
if e := docker.DockerRemove(name); e != nil {
fmt.Sprintln(e)
}

if e := Service.Create(); e != nil {
fmt.Sprintln(e)
}
}

err = Service.DockerRun()
Expand All @@ -89,14 +93,38 @@ func (Service *Service) Start() error {
}

if c, err := Service.GetRunning(); c.ID != "" {
if !discrete {
color.Print(Green(fmt.Sprintf("Successfully started %s\n", name)))
return nil
}
if err != nil {
// We cannot guarantee this container is running at this point if it is to be removed.
return fmt.Errorf(Sprintf(Red("Failed to run %s: %s\n"), Red(name), (err)))
}
return nil
} else if err != nil {
return err
}

return nil
}

// Create will perform a series of checks to see if the container starting
// is supposed be removed before-hand and will check to see if the
// container is running before it is actually started.
func (Service *Service) Create() error {

name, err := Service.GetFieldString("name")
output, _ := Service.GetFieldBool("output")

if err != nil || name == "" {
return fmt.Errorf("missing name property")
}

err = Service.DockerCreate()
if err != nil {
return err
}

l, _ := Service.DockerLogs()
if output && string(l) != "" {
fmt.Println(string(l))
}

if c, err := Service.GetRunning(); c.ID != "" {
return err
}

return nil
Expand Down Expand Up @@ -194,13 +222,33 @@ func (Service *Service) Stop() error {
}

for _, name := range container.Names {
containerName := strings.Trim(name, "/")
if e := docker.DockerStop(container.ID); e == nil {
if e := docker.DockerRemove(container.ID); e == nil {
if !discrete {
containerName := strings.Trim(name, "/")
color.Print(Green(fmt.Sprintf("Successfully removed %s\n", containerName)))
}
if !discrete {
fmt.Print(Green(fmt.Sprintf("Successfully stopped %s\n", containerName)))
}
} else {
return e
}
}

return nil
}

// Stop will stop the container.
func (Service *Service) Remove() error {

discrete, _ := Service.GetFieldBool("discrete")
container, _ := Service.GetRunning()

for _, name := range container.Names {
containerName := strings.Trim(name, "/")
if e := docker.DockerRemove(container.ID); e == nil {
if !discrete {
fmt.Print(Green(fmt.Sprintf("Successfully removed %s\n", containerName)))
}
} else {
return e
}
}

Expand All @@ -220,20 +268,10 @@ func (Service *Service) DockerLogs() ([]byte, error) {
}

name, _ := Service.GetFieldString("name")
log, e := docker.DockerContainerLogs(name)

if e != nil {
return []byte{}, err
}

if string(log) != "" {
return log, nil
}

return []byte{}, nil
return docker.DockerContainerLogs(name)
}

// DockerRun will setup and run a given container.
// DockerRun will start an existing container.
func (Service *Service) DockerRun() error {

ctx := context.Background()
Expand All @@ -243,41 +281,36 @@ func (Service *Service) DockerRun() error {
return err
}

// Ensure we have the image available:
images, _ := docker.DockerImageList()

// Specify a false boolean which we can switch to true if the image is in the registry:
imageFound := false

// Loop over our images
for _, image := range images {

// Check if it contains the desired string
if strings.Contains(Service.Config.Image, fmt.Sprint(image.RepoTags)) {
name, e := Service.GetFieldString("name")
if e != nil {
return fmt.Errorf("container config is missing label for name")
}
if err := docker.DockerContainerStart(name, types.ContainerStartOptions{}); err != nil {
return err
}

// We found the image, we don't need to pull it into the registry.
imageFound = true
return nil

}
}

}
// DockerCreate will setup and run a given container.
func (Service *Service) DockerCreate() error {

// If we don't have the image available in the registry, pull it in!
if !imageFound {
if e := Service.Setup(); e != nil {
fmt.Println(e)
}
ctx := context.Background()
cli, err := client.NewClientWithOpts()
cli.NegotiateAPIVersion(ctx)
if err != nil {
return err
}

// Sanity check to ensure we don't get name conflicts.
c, _ := docker.DockerContainerList()
for _, cn := range c {
if strings.HasSuffix(cn.Names[0], Service.Config.Labels["pygmy.name"]) {
return nil
return fmt.Errorf("container already created, or namespace is already taken")
}
}

// We need the container name.
name, e := Service.GetFieldString("name")
if e != nil {
return fmt.Errorf("container config is missing label for name")
Expand All @@ -288,10 +321,6 @@ func (Service *Service) DockerRun() error {
return err
}

if err := docker.DockerContainerStart(name, types.ContainerStartOptions{}); err != nil {
return err
}

return nil

}
6 changes: 4 additions & 2 deletions service/library/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package library

import (
"fmt"
"strings"

"github.com/fubarhouse/pygmy-go/service/color"
"github.com/fubarhouse/pygmy-go/service/interface/docker"
Expand All @@ -16,6 +17,7 @@ func Clean(c Config) {
NetworksToClean := []string{}

for _, Container := range Containers {
ContainerName := strings.Trim(Container.Names[0], "/")
target := false
if l := Container.Labels["pygmy.enable"]; l == "true" || l == "1" {
target = true
Expand All @@ -30,12 +32,12 @@ func Clean(c Config) {
if target {
err := docker.DockerKill(Container.ID)
if err == nil {
color.Print(Green(fmt.Sprintf("Successfully killed %s\n", Container.Names[0])))
color.Print(Green(fmt.Sprintf("Successfully killed %s\n", ContainerName)))
}

err = docker.DockerRemove(Container.ID)
if err == nil {
color.Print(Green(fmt.Sprintf("Successfully removed %s\n", Container.Names[0])))
color.Print(Green(fmt.Sprintf("Successfully removed %s\n", ContainerName)))
}
}
}
Expand Down

0 comments on commit a99d049

Please sign in to comment.