Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle Ctrl+C when images are being pulled when dojo action is: run #15

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
### 0.9.0 (2020-Jan-04)

* Implemented Ctrl+C (SigInt) to work for action: run for both drivers (docker and docker-compose).
The change in the run action for docker-compose driver is that now Dojo first explicitly invokes the pull action
and then it invokes the run action.
* Driver: docker-compose, action: run: fix a bug when handling a signal. Previously, when default container was
not (yet) created, there was a panic. But, it may happen that the default container is not created while
other containers are created. From now on, Dojo will not panic and it will stop the other containers.

### 0.8.0 (2020-Jan-01)

* Docker-composer driver: enable printing logs of non default docker containers either to console or to file.
Expand Down
5 changes: 4 additions & 1 deletion docker_compose_driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,7 @@ func (dc DockerComposeDriver) HandleSignal(mergedConfig Config, runID string) in
}

defaultContainerID := dc.getDefaultContainerID(names)
// it may happen that the default container is not created, but other containers are
es := dc.stop(mergedConfig, runID, defaultContainerID)
dc.Logger.Log("info", "Stopping on signal finished")
return es
Expand Down Expand Up @@ -568,6 +569,7 @@ func (dc DockerComposeDriver) HandleMultipleSignal(mergedConfig Config, runID st
}

defaultContainerID := dc.getDefaultContainerID(names)
// it may happen that the default container is not created, but other containers are
es := dc.kill(mergedConfig, runID, defaultContainerID)
dc.Logger.Log("info", "Stopping on multiple signals finished")
return es
Expand All @@ -588,7 +590,8 @@ func (dc DockerComposeDriver) getDefaultContainerID(containersNames []string) st
return contanerInfo.ID
}
}
panic(fmt.Errorf("default container not found. Were the containers created?"))
dc.Logger.Log("info", "Default container not found")
return ""
}

// example output of docker-compose ps:
Expand Down
6 changes: 0 additions & 6 deletions docker_compose_driver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -531,15 +531,9 @@ func Test_getDefaultContainerID_notCreated(t *testing.T) {
shellS := NewMockedShellServiceNotInteractive(logger)
driver := NewDockerComposeDriver(shellS, fs, logger)

defer func() {
r := recover()
assert.Contains(t, r.(error).Error(), "default container not found. Were the containers created?")
}()

names := []string{}
id := driver.getDefaultContainerID(names)
assert.Equal(t, "", id)
t.Fatal("Expected panic")
}

func Test_checkContainerIsRunning(t *testing.T) {
Expand Down
16 changes: 15 additions & 1 deletion docker_driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"os"
"strconv"
)

type DockerDriver struct {
Expand Down Expand Up @@ -110,7 +111,20 @@ func (d DockerDriver) HandleSignal(mergedConfig Config, runID string) int {
panic(err)
}
if !containerInfo.Exists {
d.Logger.Log("info", "Container already removed or not created at all, will not react on this signal")
d.Logger.Log("info", "Container already removed or not created at all")
pid := d.ShellService.GetProcessPid([]string{"docker run", runID})
if pid != 0 {
proc, err := os.FindProcess(pid)
if err != nil {
d.Logger.Log("debug", fmt.Sprintf("Nothing to do, docker run process not found: %s", err.Error()))
panic(err)
}
d.Logger.Log("info", fmt.Sprintf("Sending SIGINT to the docker run process: %s, to stop the docker pull", strconv.Itoa(pid)))
err = proc.Signal(os.Interrupt)
if err != nil {
panic(err)
}
}
return 0
}
cmd := fmt.Sprintf("docker stop %s", runID)
Expand Down
27 changes: 24 additions & 3 deletions glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion glide.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package: dojo
import: []
import:
- package: github.com/mitchellh/go-ps
- package: github.com/shirou/gopsutil/process
testImport:
- package: github.com/stretchr/testify
subpackages:
Expand Down
14 changes: 14 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,24 @@ func main() {
shellService.SetEnvironment(envService.GetVariables())

if mergedConfig.Action == "pull" {
// just pull the image(s) and exit
exitstatus := driver.HandlePull(mergedConfig)
os.Exit(exitstatus)
}

if mergedConfig.Action == "run" && mergedConfig.Driver == "docker-compose" {
// We have to first pull the image(s) in order to support ctrl+c while pulling.
// If we didn't do it, then docker-compose run command could result in starting some containers
// while pulling some images. Then, on ctrl+c we would stop the docker-compose process, which
// would stop the pulling and also the current (this) main thread. This means that there is no
// way to perform cleaning and the already started containers would be left running.
// (This is not the case for the driver: docker, but it we could implement in the same way).
exitstatus := driver.HandlePull(mergedConfig)
if exitstatus !=0 {
panic("Exit status from pulling the image was not 0")
}
}

// action is run

// This variable is needed to perform cleanup on any signal.
Expand Down
30 changes: 30 additions & 0 deletions shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import (
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"unsafe"
go_ps "github.com/mitchellh/go-ps"
gopsutil "github.com/shirou/gopsutil/process"
)

type ShellServiceInterface interface {
Expand All @@ -21,6 +24,7 @@ type ShellServiceInterface interface {
CheckIfInteractive() bool
// set environment variables, override any existing variables
SetEnvironment(variables []string)
GetProcessPid(processStrings []string) int
}

func NewBashShellService(logger *Logger) *BashShellService {
Expand All @@ -37,6 +41,32 @@ type BashShellService struct {
// a command with this struct
Environment []string
}
func (bs BashShellService) GetProcessPid(processStrings []string) int {
allProcesses, err := go_ps.Processes()
if err != nil {
panic(err)
}
for _, v := range allProcesses {
processPid := int32(v.Pid())
theProcess := gopsutil.Process{Pid: processPid}
processCmd, cmdErr := theProcess.Cmdline()
if cmdErr != nil {
return -1
}
processName := processCmd
allStringsContained := true
for _, stringToBeContained := range processStrings {
if ! strings.Contains(processName, stringToBeContained) {
allStringsContained = false
break
}
}
if allStringsContained {
return int(v.Pid())
}
}
return -1
}

func (bs *BashShellService) SetEnvironment(variables []string) {
bs.Environment = make([]string, 0)
Expand Down
47 changes: 47 additions & 0 deletions shell_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package main
import (
"fmt"
"github.com/stretchr/testify/assert"
"log"
"os/exec"
"strconv"
"sync"
"testing"
Expand Down Expand Up @@ -44,6 +46,10 @@ func (ss *MockedShellServiceNotInteractive) AppendCommandRun(command string) {
ss.Mutex.Unlock()
}

func (bs MockedShellServiceNotInteractive) GetProcessPid(processStrings []string) int {
return -1
}

// AppendCommandRun needs to be invoked on a pointer to object, because it changes the object state.
// Since this method invokes AppendCommandRun() function, it also needs to be invoked on a pointer to object.
func (bs *MockedShellServiceNotInteractive) RunInteractive(cmdString string, separePGroup bool) (int, bool) {
Expand Down Expand Up @@ -116,6 +122,9 @@ func (bs *MockedShellServiceInteractive) RunGetOutput(cmdString string, separePG
func (bs MockedShellServiceInteractive) CheckIfInteractive() bool {
return true
}
func (bs MockedShellServiceInteractive) GetProcessPid(processStrings []string) int {
return -1
}

func TestMockedShellService_CheckIfInteractive(t *testing.T){
logger := NewLogger("debug")
Expand Down Expand Up @@ -152,3 +161,41 @@ func TestBashShellService_SetEnv(t *testing.T) {
assert.Equal(t, 4, len(shell.Environment))
assert.Equal(t, "ABC=123", shell.Environment[0])
}
func startSomeCmd(name, arg string) func() {
var cmd = exec.Command(name, arg)
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
// Return a function to be invoked with "defer", so that the process is killed
// even if tests are failed. Idea from: https://stackoverflow.com/a/42310257/4457564
return func() { cmd.Process.Kill() }
}

func TestBashShellService_GetProcessPid(t *testing.T) {
var processTests = []struct {
names []string
proccessFound bool
} {
{[]string{"sleep", "5"}, true},
{[]string{"sleep", "50"}, true},
{[]string{"sleep"}, true},
{[]string{"sleep", "1"}, false},
{[]string{"blaaa"}, false},
}

deferFunc1 := startSomeCmd("sleep", "5")
deferFunc2 := startSomeCmd("sleep", "50")
defer deferFunc1()
defer deferFunc2()
for _, tt := range processTests {
logger := NewLogger("debug")
shell := NewBashShellService(logger)
pid := shell.GetProcessPid(tt.names)
if tt.proccessFound {
assert.True(t, pid > 0, tt.names)
} else {
assert.Equal(t, pid, -1, tt.names)
}
}
}
2 changes: 1 addition & 1 deletion version.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package main
const DojoVersion = "0.8.0"
const DojoVersion = "0.9.0"