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

Make start and stop functions blocking #181

Merged
merged 26 commits into from
Jun 5, 2018
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
36bdb8b
Add function WaitForContainerStatus
NicolasMahe Jun 1, 2018
e865379
Make daemon start and stop blockable
NicolasMahe Jun 1, 2018
a74d343
Update command daemon start and stop
NicolasMahe Jun 1, 2018
ead3fd9
Make service start and stop blocking
NicolasMahe Jun 1, 2018
030cd72
Improve service command
NicolasMahe Jun 1, 2018
67afce5
Improve command text
NicolasMahe Jun 1, 2018
d335451
Increase test timeout
NicolasMahe Jun 1, 2018
70c33a4
pull nginx in test
NicolasMahe Jun 1, 2018
001719a
No service mount with circleCI
NicolasMahe Jun 1, 2018
59f01fc
Prevent mount when running in CircleCI
NicolasMahe Jun 1, 2018
e79c20e
Remove useless print
NicolasMahe Jun 1, 2018
173812b
Merge branch 'container-spec' into blocking-start-stop
NicolasMahe Jun 1, 2018
03eebc8
add option to force service options mount even in CircleCI. useful fo…
NicolasMahe Jun 1, 2018
38271a2
Fix: add option to force service options mount even in CircleCI. usef…
NicolasMahe Jun 1, 2018
132b66f
Merge branch 'container-spec' into blocking-start-stop
NicolasMahe Jun 1, 2018
116687d
Merge branch 'dev' into blocking-start-stop
antho1404 Jun 1, 2018
704a0cc
Update comment on the mount hack for CircleCI
NicolasMahe Jun 4, 2018
60ea1b4
Use defer for mutex.Unlock() on service start and stop
NicolasMahe Jun 4, 2018
d22f278
Update changelog
NicolasMahe Jun 4, 2018
9676ed9
Merge commit '0005c7ca56184bf9414cc437ef40fd967a5c0b6a' into blocking…
NicolasMahe Jun 4, 2018
e2adc19
use defer for waitGroup done in service
NicolasMahe Jun 5, 2018
61f2da0
Remove timeout from container.WaitForContainerStatus function
NicolasMahe Jun 5, 2018
5e404ae
Remove return in WaitForContainerStatus
NicolasMahe Jun 5, 2018
50a6576
Reorganize daemon start to fix CodeClimate error
NicolasMahe Jun 5, 2018
7f78f01
Refacto Spinner in CLI to fix CodeClimate
NicolasMahe Jun 5, 2018
10be2d1
Fix daemon start test
NicolasMahe Jun 5, 2018
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
3 changes: 2 additions & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ jobs:
- setup_remote_docker
- run: go get -t ./...
- run: docker swarm init
- run: env DAEMON.IMAGE=mesg/daemon:$CIRCLE_SHA1 go test -timeout 60s -p 1 -coverprofile=coverage.txt ./...
- run: docker pull nginx
- run: env DAEMON.IMAGE=mesg/daemon:$CIRCLE_SHA1 go test -timeout 180s -p 1 -coverprofile=coverage.txt ./...
- run: bash <(curl -s https://codecov.io/bash)

"publish_docker_version":
Expand Down
5 changes: 4 additions & 1 deletion cmd/daemon/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"

"github.com/logrusorgru/aurora"
"github.com/mesg-foundation/core/cmd/utils"
"github.com/mesg-foundation/core/daemon"
"github.com/spf13/cobra"
)
Expand All @@ -26,10 +27,12 @@ func startHandler(cmd *cobra.Command, args []string) {
fmt.Println(aurora.Green("Daemon is running"))
return
}
s := cmdUtils.StartSpinner(cmdUtils.SpinnerOptions{Text: "Daemon is starting..."})
_, err = daemon.Start()
s.Stop()
if err != nil {
fmt.Println(aurora.Red(err))
return
}
fmt.Println(aurora.Green("Daemon is starting"))
fmt.Println(aurora.Green("Daemon is running"))
}
5 changes: 4 additions & 1 deletion cmd/daemon/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"

"github.com/logrusorgru/aurora"
"github.com/mesg-foundation/core/cmd/utils"
"github.com/mesg-foundation/core/daemon"
"github.com/spf13/cobra"
)
Expand All @@ -17,10 +18,12 @@ var Stop = &cobra.Command{
}

func stopHandler(cmd *cobra.Command, args []string) {
s := cmdUtils.StartSpinner(cmdUtils.SpinnerOptions{Text: "Stopping daemon..."})
err := daemon.Stop()
s.Stop()
if err != nil {
fmt.Println(aurora.Red(err))
return
}
fmt.Println(aurora.Green("Daemon is stopping"))
fmt.Println(aurora.Green("Daemon stopped"))
}
2 changes: 1 addition & 1 deletion cmd/service/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ To have more details, see the [detail command](mesg-core_service_detail.md).`,
}

func listHandler(cmd *cobra.Command, args []string) {
services, err := services.All()
services, err := services.All() // TODO: this should use the API
handleError(err)
for _, service := range services {
hash, _ := service.Hash()
Expand Down
5 changes: 4 additions & 1 deletion cmd/service/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/mesg-foundation/core/api/core"

"github.com/logrusorgru/aurora"
"github.com/mesg-foundation/core/cmd/utils"
"github.com/spf13/cobra"
)

Expand All @@ -25,9 +26,11 @@ var Start = &cobra.Command{
}

func startHandler(cmd *cobra.Command, args []string) {
s := cmdUtils.StartSpinner(cmdUtils.SpinnerOptions{Text: "Starting service..."})
_, err := cli.StartService(context.Background(), &core.StartServiceRequest{
ServiceID: args[0],
})
s.Stop()
handleError(err)
fmt.Println(aurora.Green("Service started"))
fmt.Println(aurora.Green("Service is running"))
}
3 changes: 3 additions & 0 deletions cmd/service/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/logrusorgru/aurora"
"github.com/mesg-foundation/core/api/core"
"github.com/mesg-foundation/core/cmd/utils"
"github.com/spf13/cobra"
)

Expand All @@ -24,9 +25,11 @@ To have more explanation, see the page [stake explanation from the documentation
}

func stopHandler(cmd *cobra.Command, args []string) {
s := cmdUtils.StartSpinner(cmdUtils.SpinnerOptions{Text: "Stopping service..."})
_, err := cli.StopService(context.Background(), &core.StopServiceRequest{
ServiceID: args[0],
})
s.Stop()
handleError(err)
fmt.Println(aurora.Green("Service stopped"))
}
13 changes: 8 additions & 5 deletions cmd/service/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,25 +90,28 @@ func testHandler(cmd *cobra.Command, args []string) {
})
handleError(err)

s := cmdUtils.StartSpinner(cmdUtils.SpinnerOptions{Text: "Starting service..."})
_, err = cli.StartService(context.Background(), &core.StartServiceRequest{
ServiceID: deployment.ServiceID,
})
s.Stop()
handleError(err)
fmt.Println(aurora.Green("Service started"))

go listenEvents(deployment.ServiceID, cmd.Flag("event").Value.String())

go listenResults(deployment.ServiceID)

time.Sleep(10 * time.Second)

time.Sleep(time.Second)
executeTask(deployment.ServiceID, cmd.Flag("task").Value.String(), cmd.Flag("data").Value.String())

<-cmdUtils.WaitForCancel()

s = cmdUtils.StartSpinner(cmdUtils.SpinnerOptions{Text: "Stopping service..."})
_, err = cli.StopService(context.Background(), &core.StopServiceRequest{
ServiceID: deployment.ServiceID,
})
fmt.Println(err)
s.Stop()
handleError(err)
fmt.Println(aurora.Green("Service stopped"))
}

func init() {
Expand Down
23 changes: 23 additions & 0 deletions container/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package container

import (
"context"
"time"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
Expand Down Expand Up @@ -48,3 +49,25 @@ func ContainerStatus(namespace []string) (status StatusType, err error) {
}
return
}

// WaitForContainerStatus wait for the container to have the provided status until it reach the timeout
func WaitForContainerStatus(namespace []string, status StatusType, timeout time.Duration) (err error) {
start := time.Now()
for {
currentStatus, err := ContainerStatus(namespace)
if err != nil {
return err
Copy link
Member

Choose a reason for hiding this comment

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

I would use some break here in order to make sure that we always exit the for loop, it's a bit easier to test

Copy link
Member Author

@NicolasMahe NicolasMahe Jun 4, 2018

Choose a reason for hiding this comment

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

Because of the new context of the for and the creation of currentStatus, err is also created. So if I use break, I'm pretty sure the err will not be assign to the return err.
If I write, the following code, go says err is shadowed during return on the return.

for {
    currentStatus, err := ContainerStatus(namespace)
    if err != nil {
	return

That's why I think if I use the break, the error will also be shadowed.

So there are 2 solutions.
The first one is to use return err as it's already the case.
The second is to created currentStatus and then assign the value:

var currentStatus StatusType
currentStatus, err = ContainerStatus(namespace)
if err != nil {
	break
}

@antho1404 What solution do you think it's the best?

Copy link
Member

Choose a reason for hiding this comment

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

I personally use the second solution all the time, we should definitely avoid shadowed variable it's the kind of things that can create bugs easily.

}
if currentStatus == status {
return nil
}
diff := time.Now().Sub(start)
if diff.Nanoseconds() >= int64(timeout) {
return &TimeoutError{
duration: timeout,
name: Namespace(namespace),
}
}
time.Sleep(500 * time.Millisecond)
}
}
48 changes: 10 additions & 38 deletions container/container_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package container

import (
"errors"
"fmt"
"testing"
"time"

Expand All @@ -18,7 +16,7 @@ func TestFindContainer(t *testing.T) {
namespace := []string{"TestFindContainer"}
startTestService(namespace)
defer StopService(namespace)
<-WaitContainerStatus(namespace, RUNNING, time.Minute)
WaitForContainerStatus(namespace, RUNNING, time.Minute)
container, err := FindContainer(namespace)
assert.Nil(t, err)
assert.NotEqual(t, "", container.ID)
Expand All @@ -43,7 +41,7 @@ func TestContainerStatusRunning(t *testing.T) {
namespace := []string{"TestContainerStatusRunning"}
startTestService(namespace)
defer StopService(namespace)
<-WaitContainerStatus(namespace, RUNNING, time.Minute)
WaitForContainerStatus(namespace, RUNNING, time.Minute)
status, err := ContainerStatus(namespace)
assert.Nil(t, err)
assert.Equal(t, status, RUNNING)
Expand All @@ -52,11 +50,9 @@ func TestContainerStatusRunning(t *testing.T) {
func TestContainerStatusStopped(t *testing.T) {
namespace := []string{"TestContainerStatusStopped"}
startTestService(namespace)
<-WaitContainerStatus(namespace, RUNNING, time.Minute)
fmt.Println("wait for running")
WaitForContainerStatus(namespace, RUNNING, time.Minute)
StopService(namespace)
<-WaitContainerStatus(namespace, STOPPED, time.Minute)
fmt.Println("wait for stop")
WaitForContainerStatus(namespace, STOPPED, time.Minute)
status, err := ContainerStatus(namespace)
assert.Nil(t, err)
assert.Equal(t, status, STOPPED)
Expand All @@ -66,50 +62,26 @@ func TestWaitForContainerRunning(t *testing.T) {
namespace := []string{"TestWaitForContainerRunning"}
startTestService(namespace)
defer StopService(namespace)
err := <-WaitContainerStatus(namespace, RUNNING, time.Minute)
err := WaitForContainerStatus(namespace, RUNNING, time.Minute)
assert.Nil(t, err)
}

func TestWaitForContainerTimeout(t *testing.T) {
namespace := []string{"TestWaitForContainerTimeout"}
startTestService(namespace)
defer StopService(namespace)
err := <-WaitContainerStatus(namespace, RUNNING, time.Nanosecond)
err := WaitForContainerStatus(namespace, RUNNING, time.Nanosecond)
assert.NotNil(t, err)
_, ok := err.(*TimeoutError)
assert.True(t, ok)
}

func TestWaitForContainerStopped(t *testing.T) {
namespace := []string{"TestWaitForContainerStopped"}
startTestService(namespace)
<-WaitContainerStatus(namespace, RUNNING, time.Minute)
WaitForContainerStatus(namespace, RUNNING, time.Minute)

StopService(namespace)
err := <-WaitContainerStatus(namespace, STOPPED, time.Minute)
err := WaitForContainerStatus(namespace, STOPPED, time.Minute)
assert.Nil(t, err)
}

// WaitContainerStatus wait for the container to have the provided status until it reach the timeout
func WaitContainerStatus(namespace []string, status StatusType, timeout time.Duration) (wait chan error) {
start := time.Now()
wait = make(chan error, 1)
go func() {
for {
currentStatus, err := ContainerStatus(namespace)
if err != nil {
wait <- err
return
}
if currentStatus == status {
close(wait)
return
}
diff := time.Now().Sub(start)
if diff.Nanoseconds() >= int64(timeout) {
wait <- errors.New("Wait too long for the container, timeout reached")
return
}
time.Sleep(500 * time.Millisecond)
}
}()
return
}
12 changes: 10 additions & 2 deletions container/service_options.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package container

import (
"os"
"strconv"

"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/swarm"
)
Expand Down Expand Up @@ -47,7 +50,7 @@ func (options *ServiceOptions) toSwarmServiceSpec() (service swarm.ServiceSpec)
},
Env: options.Env,
Args: options.Args,
Mounts: options.swarmMounts(),
Mounts: options.swarmMounts(false),
},
Networks: options.swarmNetworks(),
},
Expand All @@ -71,7 +74,12 @@ func (options *ServiceOptions) swarmPorts() (ports []swarm.PortConfig) {
return
}

func (options *ServiceOptions) swarmMounts() (mounts []mount.Mount) {
func (options *ServiceOptions) swarmMounts(force bool) (mounts []mount.Mount) {
// hack for preventing mount when in CircleCI
Copy link
Member

Choose a reason for hiding this comment

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

A bit hacky, I would add a comment TOFIX just to make sure that we can find this again when the CI allow to mount directories

Copy link
Member Author

Choose a reason for hiding this comment

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

Comment updated

circleCI, errCircle := strconv.ParseBool(os.Getenv("CIRCLECI"))
if force == false && errCircle == nil && circleCI {
return
}
mounts = make([]mount.Mount, len(options.Mounts))
for i, m := range options.Mounts {
mounts[i] = mount.Mount{
Expand Down
2 changes: 1 addition & 1 deletion container/service_options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func TestServiceOptionMounts(t *testing.T) {
},
},
}
mounts := options.swarmMounts()
mounts := options.swarmMounts(true)
assert.Equal(t, 1, len(mounts))
assert.Equal(t, "source/file", mounts[0].Source)
assert.Equal(t, "target/file", mounts[0].Target)
Expand Down
14 changes: 14 additions & 0 deletions container/type.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package container

import (
"time"
)

// StatusType of the service
type StatusType uint

Expand All @@ -8,3 +12,13 @@ const (
STOPPED StatusType = 1
RUNNING StatusType = 2
)

// TimeoutError represents an error of timeout
Copy link
Member

Choose a reason for hiding this comment

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

I think this is not a really good way to have errors I like the fact that we have the details in the error message but i'm sure we can do it better, I would just use something like that directly

errors.New(Timeout reached after " + e.duration.String() + " for ressource " + e.name)

or maybe have a function

func timeoutError(duration, resource) error {
  return errors.New(Timeout reached after " + e.duration.String() + " for ressource " + e.name)
}

or just a constant with generic error message but like that we can compare this error in the tests for example.

const TimeoutError = errors.New("Timeout error on container action")

This is a bit too much and confusing because you don't even return an error

Copy link
Member Author

Choose a reason for hiding this comment

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

It's the classic way to create new errors in go and be able to compare. Eg with type casting:

_, ok := err.(*TimeoutError)

https://blog.golang.org/error-handling-and-go

On the contrary, I think we should start creating custom error than using the default one with just a custom description. It will be way easier to debug.

Copy link
Member Author

@NicolasMahe NicolasMahe Jun 4, 2018

Choose a reason for hiding this comment

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

In the case of the TimeoutError, we can imagine than the CLI could decide to do a retry and then wait again.

Copy link
Member

Choose a reason for hiding this comment

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

it just feels like a lot of code just for a simple error that could be done in one constant but ok, let's follow the guidelines

type TimeoutError struct {
duration time.Duration
name string
}

func (e *TimeoutError) Error() string {
return "Timeout reached after " + e.duration.String() + " for ressource " + e.name
}
10 changes: 8 additions & 2 deletions daemon/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package daemon

import (
"path/filepath"
"time"

"github.com/mesg-foundation/core/config"
"github.com/mesg-foundation/core/container"
Expand All @@ -21,12 +22,17 @@ func Start() (serviceID string, err error) {
if err != nil {
return
}
return container.StartService(serviceSpec(sharedNetworkID))
serviceID, err = container.StartService(serviceSpec(sharedNetworkID))
if err != nil {
return
}
err = container.WaitForContainerStatus(Namespace(), container.RUNNING, time.Minute)
return
}

func serviceSpec(networkID string) container.ServiceOptions {
return container.ServiceOptions{
Namespace: []string{name},
Namespace: Namespace(),
Image: viper.GetString(config.DaemonImage),
Env: []string{
"MESG.PATH=/mesg",
Expand Down
2 changes: 1 addition & 1 deletion daemon/start_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func startForTest() {
panic(err)
}
_, err = container.StartService(container.ServiceOptions{
Namespace: []string{name},
Namespace: Namespace(),
Image: "nginx",
NetworksID: []string{sharedNetworkID},
})
Expand Down
7 changes: 6 additions & 1 deletion daemon/stop.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package daemon

import "github.com/mesg-foundation/core/container"
import (
"time"

"github.com/mesg-foundation/core/container"
)

// Stop the daemon docker
func Stop() (err error) {
Expand All @@ -12,5 +16,6 @@ func Stop() (err error) {
if err != nil {
return
}
err = container.WaitForContainerStatus(Namespace(), container.STOPPED, time.Minute)
return
}
Loading